A simple way to exit a loop is by using the break
statement.
if (userInput == 'Z') {
userInput = 'Z';
break;
}
Other ways would be to set your exit condition to resolve as false
, which I think is causing some issues for you.
EDIT: As @Ganea Dan Andrei noted, reading a char from cin
into an integer will cause the cin::fail()
to return true
. This can be reset by calling cin.clear()
, which will allow you to make further inputs.
userInput
is an integer, and so 'Z' would have to equal the ASCII equivalent of its char
value, which is 90
. The way you're doing it should shouldn't work. Instead, try making userInput
a char
, and then convert it to an integer so you can push it back into your vector. This might look like:
char userInput = '';
while (userInput != 'Z')
{
cout << "Please enter the homework score: ";
cin >> userInput;
homeworkScores.push_back(userInput - '0'); //Are you sure you want to push a 'Z'?
if (userInput == 'Z') {
userInput = 'Z';
break;
}
userInput = ''; // Reset your input so it doesn't keep getting pushed new values
}
What happens here is userInput - '0'
is subtracting the ASCII values of your chars, and leaving you with their integer value. There are other ways to do this, but this is a commonly used way.