c++ - cin 不会在循环中工作

标签 c++ for-loop cin

好吧,我正在尝试学习 C++,我正在做一个模拟,但 cin 对我不起作用:(

void Simulation::initialize(){
    cout<<"Choose number of players: " <<endl;
    cin>> numberOfPlayer;
    string name;
    int accurasy;
    int life;
    for(int index=0; index <=numberOfPlayer;++index){
        cout<<"Enter name, accurasy and life for player"<<index +1 <<": " <<endl;
        cin>>name;
        cin>>accurasy;
        cin>>life;
        Kombatant comb(name,accurasy,life);
        vect->push_back(comb);

    }
}

这是对我不起作用的代码。我正在尝试将玩家添加到模拟中。一切都按预期工作,直到我进入 for 循环。出于某种原因,它只在第一个循环中起作用,直到我恢复正常。然后它跳过生命输入和之后的每个输入(所有循环中的每个输入)。任何人都知道问题是什么?

最佳答案

这是因为最后一个换行符还在输入缓冲区中。因此,当您循环输入名称时,将看到换行符并为您提供一个空输入。

你必须告诉输入流显式地跳过它:

// all your input...

// Skip over the newline in the input buffer
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

关于c++ - cin 不会在循环中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15223793/

相关文章:

c++ - VC9 中的字符串流错误? "Cannot access private member"

java - 长循环计数器似乎效率很低

java - 6 次迭代后,在 for 循环中将新值赋给 double

c++ - cygwin 不识别 >> 运算符? C++

c++ - 我正在尝试使用数组从头开始创建一个 strtok 函数

c++ - 为什么类的 "Move"到 AppCode 中具有相同命名空间/名称.h 的文件导致空 .h 而所有类代码都移至 .cpp?

c++ - cin 和 boolean 输入

c++ - 如何使用 CIN 在一行中捕获两种不同的数据类型?

c++ - 未初始化变量的后果 : int vs unsigned char

r - 我应该如何使用数据库中的先前列来创建新变量