![](/img/trans.png)
[英]Why does this c++ code print out length 5 and when i'm print out string the program is automatic terminate?
[英]Why does this C++ code print out variables when it is not supposed to?
我有一个非常简单的 C++ 代码,它要求在循环中输入两个 integer 并在每次迭代中打印它们,直到用户输入字符“|”。 代码如下:
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
进行比较通常是一个坏主意,因为编译器不会对此发出警告,并且有时会产生意想不到的结果。
这个条件
if (in_int2 != '|')
只能在您输入|
的 ASCII 值时为假。 . 您可能天真地期望输入|
被转换为 ASCII 值并存储在in_int2
中。 但是,这不会发生。 相反,如果用户没有输入 integer,则std::cin >> in_int2
失败。
如果要检查用户输入,可以将输入读取为std::string
,首先检查它是否有效,然后才将其转换为int
。 通常,您应该始终检查通过std::cin
输入是否成功,方法是稍后检查 stream 的 state (就像您正确读取in_int1
)。
请注意,您的第一个示例也由于此条件的第一部分而终止:
while (cin >> in_int1 && in_int1 != '|') {
当用户输入|
然后输入失败并且cin
转换为bool
在这种情况下为false
。 第一个示例没有终止,因为&& in_int1 != '|'
. 同样,仅当您输入有效的 integer (即条件的第一部分计算为true
)并且 integer 是|
.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.