C ++ for循环输入

时间:2014-02-02 06:30:24

标签: c++ runtime-error

我创建了一个使用结构和指针来显示人物身份的项目。它的大多数工作正常,但是当它进行循环时,它只会弄乱整个程序。主要想法是以这种方式工作

for (int i = 0; i < 3; i++{
    cout << "Whatever" << endl;
    getline(cin, var_whatever[i]);
} 

因此它将循环运行3次并要求用户输入3次,但是当它运行时,它会跳过第一个输入并转到第二个输入。这是我的代码,如果有人给我这个

的解决方案,我将不胜感激
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;

//declare structure to store info about Billy
struct Son{
    string name;
    int age;
    string crush;
    string hobbies[3];
}Person;

int main(){
    int i;
    Son* info = new Son;
    info = &Person;
    //user interface
    //Person's name
    cout << "Person's name: ";
    getline(cin, info ->name); //inputs person's name
    //Person's age
    cout << "Person's age: ";
    cin >> info ->age; //inputs person's age
    //for loop to get hobbies
    for(i = 0; i <= 3; i++){ //main problem which is giving me headache
        cout << "Write your hobby[" << i <<"]: ";
        getline(cin,info ->hobbies[i]); //inputs the person hobby three times
    }
    //Person's crush
    cout << "Write your crush name: ";
    getline(cin, info ->crush); //inputs the person's crush *opitional*

    //output statement
    cout << "Name: " << info ->name << endl; //display name
    cout << "Age: " << info ->age << endl; //display age
    for(int j = 0; j < 3; j++){ //display hobbies
    cout << "Hobbies[" << j << "]: " << info ->hobbies[j] << endl;
    }
    cout << "Crush: " << info ->crush << endl; //display crush
    system("pause");
    return 0;
}

,输出

Person's name: Billy
Person's age: 25
Write your hobby[0]: Write your hobby[1]:soccer
write your hobby[2]:basketball
write your hobby[3]:Kungfu
Write your crush name: Jake
Name:Billy
Age:25
Hobbies[0]:
Hobbies[1]:soccer
Hobbies[2]:basketball
Crush: Jake

此代码输出是地狱,无论如何 谢谢你的时间

2 个答案:

答案 0 :(得分:2)

//for loop to get hobbies
for(i = 0; i <= 3; i++){

应该是

//for loop to get hobbies
for(i = 0; i < 3; i++){

您正在为i运行0,1,2和3的循环。它应该是0,1和2.

此外,如果您阅读行(getline)或读取令牌(>>),通常会更容易处理输入,但不能同时处理两者。

cout << "Person's age: ";
string age;
cin >> age;
info->age = atoi(age.c_str()); // add #include <cstring> at the top.

答案 1 :(得分:0)

问题在于:

 cin >> info ->age

问题是它读取(可能是一个int)年龄。但它没有读取行标记的结尾。所以你在流上留下了额外的EOLM。当你将这个与一个读取行getline()的命令结合使用时,除非你采取预防措施,否则它通常会混乱。

问题是由混合operator>>std::getline()引起的。在这种情况下,您可以阅读年龄(但将EOLM留在流上。第一次调用std::getline()只会从流中读取EOLM(而不是其他任何内容)。

解决此问题的最佳方法是始终一次读取一行的交互式用户输入。然后从行中解析出你想要的值。

std::string line;
std::getline(std::cin, line);

std::stringstream linestream(line);
linestream >>  info->age;

我会为几乎所有语言提供此建议,例如: Java的java.util.Scanner.next()java.util.Scanner.nextLine()