好吧,我正在尝试学习 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/