gpt4 book ai didi

c++ - While 循环重复 4 次

转载 作者:搜寻专家 更新时间:2023-10-31 01:51:45 24 4
gpt4 key购买 nike

我试图只接受整数作为输入并同时循环遍历它作为一种验证。问题是,当用户输入类似于“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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com