我只是想讓用戶輸入他們的名字/年齡並驗證它是否正確。如果沒有,那麼在程序中止之前他們會嘗試4次。然而,我的while循環不會循環,而是繼續進入下一個循環。我已經試過了,而括號中的事物變化(op != 1) (!(op = 1))
等爲什麼這個C++ While循環不起作用?
int main() {
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+ 1;
}
if (tries = 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 = 4) {
//abort the programhi
}
}
}
return 0;
}
我是相當新的C++,所以我很抱歉,如果它有一個簡單的答案。但無論如何,我已經調試了半個多小時,並且我在網上查了20多分鐘。
你明白'='是賦值,'=='是比較對嗎? – Li357
「我嘗試了括號內的東西的變體」 - 通過猜測編程確實不是你知道的一件好事。 – Rakete1111
在您的編譯器上啓用所有警告;他們會抓住這樣的事情。 '-Wall -Wextra'和'-Weverything',如果你使用的是鏗鏘聲。 – Ryan