C++ while循环中的cin不';t工作不正常(C+;+;)
该程序应检查输入的数字是否为整数。它适用于弦乐,但不适用于双打C++ while循环中的cin不';t工作不正常(C+;+;),c++,C++,该程序应检查输入的数字是否为整数。它适用于弦乐,但不适用于双打 int test; cout << "Enter the number:" << endl; while(true) { cin >> test; if (!cin || test < 0) { cout << "Wrong input, enter the number again:" << endl; cin
int test;
cout << "Enter the number:" << endl;
while(true) {
cin >> test;
if (!cin || test < 0) {
cout << "Wrong input, enter the number again:" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int检验;
库特试验;
如果(!cin | |测试<0){
试试这个:
int test;
cout << "Enter the number:" << endl;
while ( true )
{
cin >> test;
if (!(test < 0 || !cin))
break;
}
cout << "Your chosen number is: " << test << endl;
int检验;
库特试验;
如果(!(测试<0 | | |!cin))
打破
}
cout测试
是int
istream
>>运算符只是动态转换为int,然后,您将丢失小数部分
您可以将test
定义为float
,并在需要时将其转换为int
编辑:回答您上次的编辑(我没有刷新,所以错过了这一部分),发生的情况是,如果没有goto
,您将循环两次:
输入1.5
test
为1,您不输入if,因此cin
未被清除
再次循环,然后cin
立即返回
test
为0,因此输入if语句并投诉
希望这对您有所帮助您确实了解and语句,不是吗?代码工作正常,一切正常,但它没有做您想要的事情。唯一的方法是读取字符串,检查字符串是否为整数格式,然后将字符串转换为整数。这是一个很大的工作,所以除非你被告知你必须这样做,否则我不会打扰你。正如@JoachimPileborg提到的,不要使用goto
语句;这被认为是一种糟糕的编程实践。改用break
和continue
语句。不,它不工作,程序不工作。例如,输入“1.2”。break没有任何区别,我已经试过了。可以使用字符串吗?