【发布时间】:2020-08-07 19:05:33
【问题描述】:
我有一个非常简单的 C++ 代码,它要求在一个循环中输入两个整数,并在每次迭代中打印它们,直到用户输入字符“|”。代码如下:
int main() {
int in_int1;
int in_int2;
cout << endl << "Enter numbers one at a time. Enter '|' to end.";
cout << endl << ">> ";
while (cin >> in_int1 && in_int1 != '|') {
cout << ">> ";
cin >> in_int2;
if (in_int2 != '|') {
cout << "int 1: " << in_int1 << endl;
cout << "int 2: " << in_int2 << endl;
cout << endl << ">> ";
} else break;
}
return 0;
}
这是一个完全符合预期的示例运行:
Enter numbers one at a time. Enter '|' to end.
>> 12
>> 44
int 1: 12
int 2: 44
>> 98
>> 45
int 1: 98
int 2: 45
>> |
程序按预期终止。
这是一个奇怪的地方的示例:
Enter numbers one at a time. Enter '|' to end.
>> 54
>> |
int 1: 54
int 2: 0
程序终止
如您所见,即使代码从未输入 if-block,它也会打印值。
发生了什么?为什么程序打印两个整数而没有进入打印指令所在的块?每次我输入第一个数字并输入“|”时都会发生这种情况在第二个输入提示。
更新
以下代码按预期工作:
int main() {
int in_int1;
int in_int2;
cout << endl << "Enter numbers one at a time. Enter '|' to end.";
cout << endl << ">> ";
while (cin >> in_int1) { // CHANGE 1: the second condition was unnecessary
// because the condition fails when user enters non numeric
// character anyway. Besides, I was comparing int with char.
cout << ">> ";
if (cin >> in_int2) { // CHANGE 2: similar logic applies here.
cout << "int 1: " << in_int1 << endl;
cout << "int 2: " << in_int2 << endl;
cout << endl << ">> ";
} else {
break;
}
}
return 0;
}
而不是输入'|'为了终止程序,我在这里的评论者的帮助下发现,输入 124 会使我的程序按预期运行。我发现将int 与没有显式转换的char 进行比较通常是一个坏主意,因为编译器不会对此发出警告,而且有时会产生意想不到的结果。
【问题讨论】:
-
您将
int与char进行比较 -
尝试阅读“|”作为整数失败。你可以通过输入 124 让它停止。(练习:找出原因。)
-
用
cin >> in_int2尝试读取一个整数,但|不是整数。 -
@PPrasai 因为那是
'|'的ASCII 值。并且您的第一次运行终止,因为cin条件变为false当它没有读取整数时 -
“如果是这种情况,那么 while 循环内的第一个输入也不应该起作用”——这是一个过早的结论。您的
while循环会检查超出您的if语句检查的额外条件...
标签: c++