在输入流失败后对输入变量的影响 [英] Effects on Input Variable after Failed Input Stream

查看:160
本文介绍了在输入流失败后对输入变量的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以下代码。

#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)会更好,但我不明白一个具体的发生。
如果我提供一个无效的输入,循环变为无穷大,因为输入流进入failbit状态。我的问题是,输入变量 i 会发生什么?在我的情况下,它变为0,无论输入的以前的值。为什么在无效输入后更改为0?这是一个预定义的行为?

I know that using while (std::cin >> i) would have been better but I don't understand a specific occurrence. If I provide an invalid input, the loop becomes infinite because the Input Stream enters a failbit state. My question is that what happens to the input variable i? In my case, it becomes 0 regardless of the previous value entered. Why does it change to 0 after an invalid input? Is this a predefined behaviour?

推荐答案

你得到零,因为你有一个前C ++ 11编译器。在失败时保持输入值不变在最新标准中是新的。旧标准需要以下内容:

You get zero because you have a pre-C++11 compiler. Leaving the input value unchanged on failure is new in the latest standard. The old standard required the following:


如果提取失败,则会将零写入值,并设置failbit。如果
提取导致值太大或太小以适合
值,std :: numeric_limits :: max()或std :: numeric_limits :: min()
被写入, failbit标志设置。

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 给编译器使用新的行为。

For gcc, you need to pass -std=c++11 to the compiler to use the new behavior.

这篇关于在输入流失败后对输入变量的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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