[英]Programming Principles and Practice: chapter 4 drill part 1
我似乎無法讓這個程序正常工作。 我可以讓它接受兩個整數並將它們打印到屏幕上。 但是當'|'出現時我無法讓程序終止用來。 一旦它進入它無限循環。 這是我到目前為止的代碼:
#include "../../std_lib_facilities.h"
int main()
{
int num1 = 0;
int num2 = 0;
char counter = '\0';
cout << "Please enter two integers and press enter. \n";
bool test = true;
while (counter != '|')
{
cin >> num1 >> num2;
cout << "Your numbers are: " << num1 << " " << num2 << endl;
if (cin.fail())
{
cout << "Goodbye!\n";
test = false;
}
else (counter != '|');
cout << "Enter more numbers or press '|' to exit.\n";
}
system("pause");
}
您在 while 循環中使用了錯誤的條件。 你永遠不會改變counter
所以循環永遠不會結束。 但是,如果輸入失敗,您會在 while 循環中將test
更改為false
。 您可以更改 while 循環的條件以使用test
代替
while(test)
{
//...
}
由於不再使用counter
因此您可以完全擺脫它。
請注意,除非您更改為接受字符串並解析輸入,否則任何會導致cin
失敗的輸入都將結束循環,而不僅僅是一個|
.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.