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;
}
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.
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 LITE 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.
Bookmarks