CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    Oct 2008
    Posts
    59

    Question 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;
    }

  2. #2
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    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.

  3. #3
    Join Date
    Jul 2009
    Location
    India
    Posts
    835

    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');

  4. #4
    Join Date
    Jul 2009
    Location
    India
    Posts
    835

    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.

  5. #5
    Join Date
    Jun 2009
    Location
    France
    Posts
    2,513

    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
  •  





Click Here to Expand Forum to Full Width

Featured