[英]If/else if not executing even though it appears conditions are met inside of a while loop
[英]C++ While loop terminating even though conditions are not met
我希望程序不斷請求值進行計算,直到標志為真,然后程序必須停止,但它只執行一次。 我不知道我是否以正確的方式使用 char,或者是否有更好的方法來執行這些帶有標志的 while 循環。 任何幫助都會很棒。[在此處輸入圖片描述][1]
int main()
{
displayMenu();
bool flag = false;
while(!flag)
{
int choice = 0; int val1 = 0; int val2 = 0; int ans = 0;
cout << "Enter your choice (1-5): ";
cin >> choice;
cout << "\nEnter integer 1: ";
cin >> val1;
cout << "\nEnter integer 2: ";
cin >> val2;
if(choice < 0 || choice > 5)
{
cout << "\nEnter a choice between 1-5: ";
cin >> choice;
}
if (choice == 1)
{
ans = Add(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 2)
{
ans = Subtract(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 3)
{
ans = Multiply(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 4)
{
ans = Divide(val1,val2);
cout << "\nResult: " << ans << endl;
}
if (choice == 5)
{
ans = Modulus(val1,val2);
cout << "\nResult: " << ans << endl;
}
char c_flag[] = "n";
cout << "Press Y or y to continue: ";
cin >> c_flag;
if(c_flag == "y" || c_flag == "Y")
{
flag = false;
}
else
{
flag = true;
}
}
return 0;
}
對於數據類型char c_flag[]
,很可能永遠不會滿足條件c_flag == "y"
,因為您正在比較兩個(不同的)指針值,而不是它們的內容。
改用std::string c_flag
,至少您的條件應該按預期工作。
你也可以寫
char c_flag[] = "y";
...
if (strcmp(c_flag,"y")==0) ...
但我更喜歡std::string
char c_flag[] = "y"
原因如下:使用char c_flag[] = "y"
,你分配一個大小為 2 的數組(包括字符串終止字符); 使用cin >> c_flag
,如果輸入多個字符,則會超出數組長度並產生未定義的行為。 相反,使用std::string
,變量將在必要時“增長”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.