3

考虑下面的代码,它接受一个整数输入,然后打印 cin 流状态:

#include <iostream>  
using namespace std;

int main()
{
    int number;
    cout<<"Enter a number \n";
    cin>>number;
    cout<<cin.rdstate()<<endl;
    return 0;
}

如果输入的数字是“zzzz”,则 rdstate 返回值 4。
如果输入的数字是“10zzzz”,则 rdstate 返回值 0,数字的值为 10,输入流中的“zzzz”它。

我的问题是:
1. 为什么不将“10zzzz”的输入视为无效输入(至少应该设置一个故障位。)
2. 检测和处理这种情况的优雅解决方案是什么。

谢谢!!!

4

1 回答 1

1

首先,我想问一下您要做什么:

cout<<cin.rdstate()<<endl;

阅读此页面以正确使用 rdstate() http://www.cplusplus.com/reference/iostream/ios/rdstate/

第二:要检查输入是字符串类型还是整数类型,您可能需要添加一些额外的东西,将输入字符串转换为整数数据,并在输入无效输入时响应错误消息。

因此,这将帮助您:

int main() {

 string input = "";

 // How to get a string/sentence with spaces
 cout << "Please enter a valid sentence (with spaces):\n>";
 getline(cin, input);
 cout << "You entered: " << input << endl << endl;

 // How to get a number.
 int myNumber = 0;

 while (true) {
   cout << "Please enter a valid number: ";
   getline(cin, input);

   // This code converts from string to number safely.
   stringstream myStream(input);
   if (myStream >> myNumber)
     break;
   cout << "Invalid number, please try again" << endl;
 }
 cout << "You entered: " << myNumber << endl << endl;

 // How to get a single char.
 char myChar  = {0};

 while (true) {
   cout << "Please enter 1 char: ";
   getline(cin, input);

   if (input.length() == 1) {
     myChar = input[0];
     break;
   }

   cout << "Invalid character, please try again" << endl;
 }
 cout << "You entered: " << myChar << endl << endl;

 cout << "All done. And without using the >> operator" << endl;

 return 0;
}
于 2012-05-09T09:18:21.307 回答