JimmyCode JimmyCode - 3 months ago 9
C++ Question

Why won't this C++ While loop work?

I'm simply trying to get the user to put in their name/age and verify if it's correct. If not then they get 4 tries before the program will abort. However my while loops don't loop, instead they just continue on to the next loop. I've tried a variation of things inside the while parenthesis

(op != 1) (!(op = 1))
etc.

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;
}


I'm fairly new to C++ so I'm sorry if it does have a simple answer. But anyway, I've been debugging this for over half an hour and I looked online for 20+ minutes.

Answer
if (tries = 4) {
            //abort the program
        }   

Change this to

if (tries == 4) {
            //abort the program
        }   

And

f (op == 2) {
            cout << "Please Try Again!";
            tries+= 1; // tries+ 1;
            }

You can increment value in C++ like this tries+ 1;. Either use tries+= 1; or tries++;