c++ - 为什么在 C++ 中输入 '|' 时这段代码会导致无限循环?

标签 c++ loops cin

我正在阅读编程:使用 C++ 的原理和实践(第 2 版)
我发现了这个问题:

  • 编写一个由 while 循环组成的程序,该循环(每次循环)读入两个 整数,然后打印它们。终止'|'时退出程序已输入。

这是我试过的:

#include <iostream>
using namespace std;
int main () {
int x, y;
while (x != '|' || y != '|'){
    cin >> x;
    cin >> y;
    cout << x << endl;
    cout << y << endl;
}

return 0;
}

当'|'输入时,它会打印类似无限循环的内容,意外的输出。

  • 那里发生了什么事?
  • 我做错了什么?

最佳答案

首先,你没有设置xy在将它们与 '|' 进行比较之前与任何事物进行比较在while环形。这意味着它们可能具有任意值,您的循环甚至可能不会开始。


至于为什么您会看到一个无限循环,因为变量的类型是int , cin >> something将尝试将您输入的字符转换为一个整数并将其放入变量中。

如果这些字符的初始序列形成有效整数(例如,它是| 字符),则cin >>将失败,变量将保持不变,输入流将保持原样。

因此,当您再次获得下一个整数时,| 仍然在输入流中,完全相同的事情会再次发生,无穷无尽——注意那个拉丁短语和你的问题标题之间的相似性:-)


要解决这个问题,您可以尝试逐个字符地向前看,看看您是否有 |在流中。如果是这样,请退出。如果不是,请尝试使用正常的 if (stream >> variable) 获取两个整数方法。

这可以通过 cin.peek() 来完成检查下一个字符,cin.get()删除一个字符。您还必须考虑到 peek 都不是也不get将以 operator>> 的方式跳过空格可能。

这样的事情应该是一个好的开始:

#include <iostream>
#include <cctype>

int main() {
    int x, y;

    while (true) {
        // Skip all white space to (hopefully) get to number or '|'.

        while (std::isspace(std::cin.peek())) std::cin.get();

        // If it's '|', just exit, your input is done.

        if (std::cin.peek() == '|') break;

        // Otherwise, try to get two integers, fail and stop if no good.

        if (! (std::cin >> x >> y)) {
            std::cout << "Invalid input, not two integers\n";
            break;
        }

        // Print the integers and carry on.

        std::cout << "You entered " << x << " and " << y << "\n";
    }

    return 0;
}

使用各种测试数据表明它涵盖了所有情况(我能想到的):

pax$ ./myprog </dev/null
Invalid input, not two integers

pax$ echo hello | ./myprog
Invalid input, not two integers

pax$ echo 1 | ./myprog
Invalid input, not two integers

pax$ echo 1 2 | ./myprog
You entered 1 and 2
Invalid input, not two integers

pax$ printf '1 2|' | ./myprog
You entered 1 and 2

pax$ printf '1 2\n3 4\n5     6 7   8   \n|' | ./myprog
You entered 1 and 2
You entered 3 and 4
You entered 5 and 6
You entered 7 and 8

pax$ printf '1 10     11   12   13    14    |   ' | ./myprog
You entered 1 and 10
You entered 11 and 12
You entered 13 and 14

关于c++ - 为什么在 C++ 中输入 '|' 时这段代码会导致无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291263/

相关文章:

C++子串多字节字符

c++ - eclipse CDT : How to relink static libraries without Project Clean>>Project Rebuild

java - 如何在循环中组合 if 语句

c - 带有 C 语言函数的简单无限循环

c++ - 无字母循环

c++ - C/C++ - 如何管理视频游戏中的循环?

c++ - 如何在 C++ 中使用智能指针实现接口(interface)隔离原则?

javascript - setTimeout/clearTimeout 危险吗?

C++ 检查 cin 的输入是否有正确的数据

c++ - 将用户输入验证为 int 时陷入无限循环