正确使用cin.fail()的方法 [英] Correct way to use cin.fail()

查看:495
本文介绍了正确使用cin.fail()的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 cin.fail(); 的正确方法是什么?

What is the correct way to use cin.fail();?

我正在编写程序您需要在其中输入内容的地方。不清楚是否需要输入数字或字符。当用户输入字符而不是数字时,控制台会发疯。如何使用 cin.fail()修复此问题?

I am making a program where you need to input something. It is not very clear if you need to input a number or character. When a user inputs a character instead of a number the console goes crazy. How can I use cin.fail() to fix this?

还是有更好的方法?

推荐答案

cin.fail()如果最后一个cin命令失败,则返回true,

cin.fail() returns true if the last cin command failed, and false otherwise.

示例:

int main() {
  int i, j = 0;

  while (1) {
    i++;
    cin >> j;
    if (cin.fail()) return 0;
    cout << "Integer " << i << ": " << j << endl;  
  }
}

现在假设您有一个文本文件-input.txt它的内容是:

Now suppose you have a text file - input.txt and it's contents are:

  30 40 50 60 70 -100 Fred 99 88 77 66

在短程序上运行时,结果将是:

When you will run above short program on that, it will result like:

  Integer 1: 30
  Integer 2: 40
  Integer 3: 50
  Integer 4: 60
  Integer 5: 70
  Integer 6: -100

在读完第七个之后退出时,它将在第六个值之后不再继续单词,因为它不是整数: cin.fail()返回 true

it will not continue after 6th value as it quits after reading the seventh word, because that is not an integer: cin.fail() returns true.

这篇关于正确使用cin.fail()的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆