c++ - C++中的无限循环

标签 c++ stream infinite-loop biginteger largenumber

<分区>

我正在学习 C++ 并在学习过程中编写小程序。下面是一个这样的程序:

// This program is intended to take any integer and convert to the
// corresponding signed char.

#include <iostream>

int main()
{
  signed char sch = 0;
  int n = 0;
  while(true){
    std::cin >> n;
    sch = n;
    std::cout << n << " --> " << sch << std::endl;
  }
}

当我运行这个程序并将输入保持在相当小的绝对值时,它的行为符合预期。但是当我输入更大的输入时,例如 10000000000,程序会重复吐出相同的输出。某些输入组合会导致不稳定的行为。例如:

#: ./int2ch
10
10 --> 

10000000000
10 -->

10 -->

10 -->

10 -->

程序吐出“10 -->”直到它被杀死。 (对于这种特定的输入序列,程序的输出会不规律地改变速度。)我还注意到,大值的输出取决于先前的合法输入以及当前非法输入的值。

这是怎么回事? (我不关心修复程序,这很容易。我想了解它。)

最佳答案

基本上您的 cin 流处于失败状态,因此当您尝试读取它时会立即返回。像这样重写您的示例:

#include <iostream>

int main()
{
  signed char sch = 0;
  int n = 0;
  while(std::cin >> n){
    sch = n;
    std::cout << n << " --> " << sch << std::endl;
  }
}

cin >> n 将返回对 cin 的引用,您可以在条件中测试它的“良好性”。所以基本上“while(std::cin >> n)”是说“虽然我仍然可以成功地从标准输入读取,但执行以下操作”

编辑:它重复输出输入的最后一个好值的原因是因为那是在 n 中成功读取的最后一个值,读取失败不会改变 n 的值

编辑:如评论中所述,您可以清除错误状态并重试,这样的操作可能会起作用,而只是忽略错误的数字:

#include <iostream>
#include <climits>

int main() {
    signed char sch = 0;
    int n = 0;
    while(true) {
        if(std::cin >> n) {
            sch = n;
            std::cout << n << " --> " << sch << std::endl;
        } else {
            std::cin.clear(); // clear error state
            std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
        }
    }
}

关于c++ - C++中的无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/266665/

相关文章:

java - 为什么这个 while 循环陷入无限循环?

c++ - 为什么 gdb 在 !=/== 和 &&/|| 时不能计算函数组合在一个表达式中?

c++ - QGraphicsTextItem 是否支持垂直居中对齐?

javascript - EasyRTC 一般身份验证错误

java - 为什么耗时的测量是错误的?

c++ - 发送 std::endl 到流给出内存地址

c++ - 当应用程序没有焦点时检测按键

c++ - 在 C++ 中使用堆栈和 vector 以相反顺序打印字符串

c - 如何终止 Turbo C 中的无限循环?

c - 8 个皇后拼图 : using random numbers causes infinite loop