1,105,578 Community Members

looping,error

Member Avatar
SamuraiGhost
Newbie Poster
3 posts since Feb 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
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;
Member Avatar
livinFuture
Newbie Poster
17 posts since Jan 2011
Reputation Points: 0 [?]
Q&As Helped to Solve: 1 [?]
Skill Endorsements: 0 [?]
 
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 three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article