1.11M Members

looping,error

 
0
 

I have code that will ask for the day of the week but is there a way to make it ask the question again if the user doesn't enter one of the 7 days provided?

string TheDay()
{
	string whichday;
	cout<<"Please provide a day of the week - ex. Mo Tu We Th Fr Sa Su"<<endl;
	cin>> whichday;
	system("cls");
	transform(day.begin(), day.end(), day.begin(), tolower);
	return whichday;
 
0
 

Well let's look at what you want to do logically.
[] prompt user to provide day of week
[] read user input
[] check user input for validity
+ if user input is valid; do what you need to do
- if user input is invalid; prompt user about incorrect input and ask again

Since you don't know how many times the user may enter incorrect input you could use a do while loop to check for validity. That is logically, while(input is false/invalid) prompt user for new input. You will need a flag of type bool.

bool inputValid; // should be true if input is accepted
do 
{
 cout << "That isn't a day of the week!\n" << "Please provide a day of the week - ex. Mo Tu We Th Fr Sa Su" << endl;
 cin >> whichday;
// you'll need code in the if statement to check whichday against accepted input
if (/*whichday is accepted then*/) inputValid = true;
else /*whichday is not accepted*/ inputValid = false;
}
while(!inputValid); // while input is not valid
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article