Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/153.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ while循环中的cin不';t工作不正常(C+;+;)_C++ - Fatal编程技术网

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没有任何区别,我已经试过了。可以使用字符串吗?