1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Allowing the user to re run a program in c++

  1. Dec 21, 2012 #1
    1. The problem statement, all variables and given/known data

    I am making mini programs where there some calculations going on and when all that is done my program is to ask the user if he wants to repeat the calculations or not. If he does then the program is to restart and if he doesn't then he can close the window by pressing the enter key.
    I am using visual c++ 2008 express which closes the window when the program executes its last line of code. I am also very new to c++.

    2. Relevant equations



    3. The attempt at a solution
    Code (Text):
    char repeat = 'y';
    //repeat is the variable which stores y or n in order to determine
    //whether to repeat the calculations or not
    if (repeat == 'y')
    {
    *All the calculations code here*
    }
    cout<< "Would you like to repeat the calculations? ";
    cin>> repeat;
    if (repeat=='n')
    {
    cout<<"press enter to close the window.";
    }
     
    The problem is that if I do this then the program ends even if I enter y. A solution around this is to replace the if statements with while loops. If I do that however if the user enters n the program goes into an infinite loop. But the program works fine if I just get rid of

    Code (Text):
    cout<< "Would you like to repeat the calculations? ";
    cin>> repeat;
    if (repeat=='n')
    {
    cout<<"press enter to close the window.";
    }
    I want the program to give the user the ability the close the window by pressing enter. So what do you think is happening and how can I get around that? My compiler isn't giving me any errors so its my code.
     
  2. jcsd
  3. Dec 22, 2012 #2

    mfb

    User Avatar
    2016 Award

    Staff: Mentor

    do while has the logic you want here.

    Code (Text):
    do {
      //do stuff
      //now ask for user input
      cin>> repeat;
    } while (repeat=='y');
     
  4. Dec 22, 2012 #3
    ah thanks that worked
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook