It doesn't actually crash when the user enters something other than y or n, it simply terminates normally.
One way to deal with that is to use a loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
char Yes = 'y';
char No = 'n';
char ansQues;
do
{
cin >> ansQues;
if (ansQues == Yes)
{
// etc.
}
else if (ansQues == No)
{
// etc.
}
else
{
cout << "Sorry, I don't understand, could you just put 'y' or 'n' please " << endl;
}
} while (ansQues != Yes && ansQues != No);
|
Note, in your code, the variables
Yes
and
No
are defined but your code makes no use of them. (I did use them in the example above).
If you want to allow for both upper and lower case responses, one way is to test for either possibility:
|
if (ansQues == 'y' || ansQues == 'Y')
|
another way is to convert the input to either upper or lower case before testing its value:
1 2 3
|
cin >> ansQues;
ansQues = tolower(ansQues);
if (ansQues=='y')
|
In order to allow for all possible variations, such as 'y', 'Y', "YES", "yes", "Yes", "yeah" .. and so on, change
ansQues
to be of type
string
instead of
char
and test for each possibility, separated by the logical
or operator
||
as i showed in the 'y' 'Y' example.