我试图只接受整数作为输入,并同时循环它作为一种验证。问题是,当用户输入“Two”之类的内容时,while 循环会在再次询问用户之前对输入进行 3 次不同的处理。有没有办法防止这种情况发生并跳过 3 次迭代?
cout << "Enter Student ID: ";
while(!(cin >> id))
{
cout << "\nERROR: Please enter a Positive Whole Number" << endl;
cin.clear();
cin.ignore ();
cout << "Enter Student ID: ";
}
最佳答案
你可以使用这个。
cin.ignore (std::numeric_limits<streamsize>::max (), '\n') ;
它会跳过所有行,并且无论您输入多少无效字符,您都不会获得额外的循环迭代。
关于c++ - While 循环重复 4 次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13549190/