【问题标题】:C++ Checking if input is a int and redo the input until it is a intC++ 检查输入是否为 int 并重做输入直到它为 int
【发布时间】:2013-11-06 01:46:01
【问题描述】:

我目前正在做一个简单的“你几岁”计算器。但我想检查用户输入的是 int 还是 char。所以我做了这个:

 if (!cin) {

cout << "Error" << endl; 
cin >> year;

}

但如果我这样做并输入一个字符,它只会通过并且不允许新的输入。

【问题讨论】:

  • 它仍然设置了标志和错误的输入。
  • 没有循环,你为什么会期待它再次出现

标签: c++ char int


【解决方案1】:

参考:cin for an int inputing a char causes Loop that is supposed to check input to go wild

这是重复的,但规范的答案是:

std::cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

然后执行以下操作:

int year;

 while (!(std::cin >> year)) {
    std::cin.clear(); // clears the error flags
    // this line discards all the input waiting in the stream
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    std::cout << "error" << std::endl;
 }

// do something with year

所以如果你的输入看起来像:

a
b
c
42

会打印3次错误。

【讨论】:

  • 谢谢,我明天试试!
猜你喜欢
  • 2018-04-14
  • 2018-05-08
  • 2012-08-17
  • 2017-07-19
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 2013-11-06
  • 1970-01-01
相关资源
最近更新 更多