-
February 20th, 2011, 09:41 PM
#1
Restarting the program
I have a simple program showm below that asks the user for a choice of drink. But if they enter a value that is incorrect, how can you restart the program? Do I use a do...while?
Thanks
Code:
#include <iostream>
using namespace std;
int main()
{
int choice;
cout << " Please enter a choice of drink (1-3): \n";
cin >> choice;
switch (choice)
{
case 1:
cout <<"Cola";
break;
case 2:
cout <<"Orange";
break;
case 3:
cout <<"Water";
break;
default:
cout <<"Error. choice was not valid, here is your money back";
}
system("Pause");
return 0;
}
-
February 20th, 2011, 10:29 PM
#2
Re: Restarting the program
Don't think of it as "restarting the program". Just use a loop to jump back to the thing you want to do repeat in order to fix the input.
-
February 21st, 2011, 12:36 AM
#3
Re: Restarting the program
Simple approach to repeat the same goes here..
Code:
char c;
do
{
//your code which should repeat..
cout<<"continue (y/n): ";
cin>>c;
}while (c!='n');
-
February 21st, 2011, 12:37 AM
#4
Re: Restarting the program
And concept of restarting the whole program ie: the exe is complex but can be achieved. But for a simple console application I think I answered what you needed.
-
February 21st, 2011, 03:08 AM
#5
Re: Restarting the program
If you want to break out and restart your program from anywhere, then a try-catch construct might be better addapted than a plain while loop.
In any case, make sure your constructs are RAII (or make sure you correctly clean-up) to avoid memory leaks.
The usual alternative is to just exit the program, and have it restart from an external source. That's what 99% of command line apps do.
Is your question related to IO?
Read this C++ FAQ article at parashift by Marshall Cline. In particular points 1-6.
It will explain how to correctly deal with IO, how to validate input, and why you shouldn't count on "while(!in.eof())". And it always makes for excellent reading.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|