#include<iostream>
usingnamespace std;
int main()
{
char ans; // The user's answer to the question
int age; // The user's age
bool correct; // The boolean flag
////////////////////////////////
// Beginning of your code
// Ask the user a yes/no question and make sure the response is
// either y or n
cout <<"Do you like the color blue? (y/n): ";
cin >> ans;
// if he enters another characters other that y and n it will prompt the user to enter the correct characters
// Get the user's age
// Make sure the user enters her age as a number
cout <<"Enter your age as an integer: ";
cin >> age;
// End of your code
////////////////////////////////
cout << "Thanks for your input!" << endl;
system("pause");
return 0;
}
Without knowing your assignment we have no idea what you are supposed to do with it either. Only thing I could possibly see if using it to confirm that the user entered a proper input for each question. However if that's the intention of the assignment it would seem a bit out of the scope of this exercise since it would most likely require some kind of conditional expression.
I need to ask the user for input and loop until he enters valid input.I need to ask a yes or no question (y/n) and then check if the input is valid. then ask the user to enter the age.And again if the user does not enter a number for the age question, it will prompt the user to enter valid input
the output should look like this
Do you like the color blue?(y/n) : x
incorrect value
Do you like the color blue? (y/n): n
Enter age as integer: abc
You must enter an integer
Enter age as integer: 20
#include<iostream>
usingnamespace std;
int main()
{
char ans; // The user's answer to the question
int age; // The user's age
bool correct = false; // The boolean flag
////////////////////////////////
// Beginning of your code
// Ask the user a yes/no question and make sure the response is
// either y or n
cout <<"Do you like the color blue? (y/n): ";
cin >> ans;
while(!correct)
{
if(ans != 'y' && ans !='n')
{
cout << "Incorrect value" <<endl;
cout << "Do you like the color blue? (y/n): ";
cin >> ans;
}
}
// Get the user's age
// Make sure the user enters her age as a number
// End of your code
////////////////////////////////
cout << "Thanks for your input!" << endl;
system("pause");
return 0;
}
Two ways. 1) extract the age as a string, check that the string is a number, and then convert the string to an integer. 2) extract the age as an int and check to see that the extraction was successful.
When you use >> to extract a number, and the user enters letters, you set a fail bit on the cin object. You will want to extract the number and check if cin is good. If it isn't, clear it, ignore the input (it would still be there), and try again.