首先,在while循环中比较' | '之前,您尚未将x或y设置为任何值。这意味着它们可能具有任意值,而您的循环甚至可能不会开始。
至于为什么会看到无限循环,因为变量的类型为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) {
while (std::isspace(std::cin.peek())) std::cin.get();
if (std::cin.peek() == '|') break;
if (! (std::cin >> x >> y)) {
std::cout << "Invalid input, not two integers\n";
break;
}
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
x
和y
是整数,不是字符。它们不能是'|'。在输入之前使用cin.peek()
检查'|'。 - eesiraedx
和y
,但没有将它们初始化为任何值。 - Tas&&
替代||
,并考虑使用do...while
循环。 - Remy Lebeau