首先,在将while 循环中的'|' 与'|' 进行比较之前,您尚未将x 或y 设置为任何值。这意味着它们可能具有 任意 值,并且您的循环甚至可能不会开始。
至于为什么你会看到一个无限循环,因为变量的类型是int,cin >> something 会尝试将你输入的字符翻译成 em> 一个整数并将其放入变量中。
如果这些字符的初始序列不是形成一个有效的整数(例如,它是| 字符),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