gpt4 book ai didi

c++ - 如何制作过滤掉非整数的 C++ 程序?

转载 作者:太空宇宙 更新时间:2023-11-03 10:35:50 24 4
gpt4 key购买 nike

像这样

cout << "Enter the number of columns: " ;
cin >> input ;
while( input != int ){
cout << endl <<"Column size must be an integer"<< endl << endl;
cout << "Enter the number of columns: " ;
cin >> input ;
}

最佳答案

cin会为你做这个,有点。 cin如果它收到与 input 类型不同的内容,将会失败.你可以做的是:

int input;
while(!(cin >> input))
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << endl <<"Column size must be an integer"<< endl << endl;
cout << "Enter the number of columns: " ;
}

cin.clear()清除错误位,cin.ignore()清除输入流。我正在使用 number_limits要获得流的最大大小,需要您 #include<limits> .或者,您可以只使用一个大数字或一个循环。

关于c++ - 如何制作过滤掉非整数的 C++ 程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3826281/

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