加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 输入流失败后对输入变量的影响

发布时间:2020-12-16 09:45:57 所属栏目:百科 来源:网络整理
导读:我正在处理以下代码. #include iostreamint main(){ std::cout "Enter numbers separated by whitespace (use -1 to quit): "; int i = 0; while (i != -1) { std::cin i; std::cout "You entered " i 'n'; }} 我知道使用while(std :: cin i)本来会更好,但
我正在处理以下代码.

#include <iostream>

int main()
{
  std::cout << "Enter numbers separated by whitespace (use -1 to quit): ";
  int i = 0;
  while (i != -1) {
    std::cin >> i;        
    std::cout << "You entered " << i << 'n';
  }
}

我知道使用while(std :: cin>> i)本来会更好,但我不明白具体的情况.
如果我提供无效输入,则循环变为无限,因为输入流进入故障位状态.我的问题是输入变量i会发生什么?就我而言,无论先前输入的值如何,它都变为0.输入无效后为什么会变为0?这是预定义的行为吗?

解决方法

你得到零,因为你有一个pre-C 11编译器.在失败时保持输入值不变是最新标准中的新功能.旧标准要求如下:

If extraction fails,zero is written to value and failbit is set. If
extraction results in the value too large or too small to fit in
value,std::numeric_limits::max() or std::numeric_limits::min()
is written and failbit flag is set.

(source)

对于gcc,您需要将-std = c 11传递给编译器以使用新行为.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读