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

  • Thread starter Thread starter wahaj
  • Start date Start date
  • Tags Tags
    C++ Program
Click For Summary
The user is developing a C++ program that performs calculations and prompts the user to repeat them or exit. The initial approach using if statements leads to the program closing prematurely, even when the user chooses to repeat. A suggested solution involves using a do-while loop to maintain the program's execution until the user decides to exit by entering 'n'. The user confirmed that implementing the do-while loop resolved the issue, allowing for repeated calculations and a proper exit method by pressing enter. This approach is effective for managing user input and program flow in C++.
wahaj
Messages
154
Reaction score
2

Homework Statement



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++.

Homework Equations





The Attempt at a Solution


Code:
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:
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.
 
Physics news on Phys.org
do while has the logic you want here.

Code:
do {
  //do stuff
  //now ask for user input
  cin>> repeat;
} while (repeat=='y');
 
ah thanks that worked
 

Similar threads

  • · Replies 2 ·
Replies
2
Views
3K
Replies
3
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 24 ·
Replies
24
Views
2K
  • · Replies 2 ·
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 6 ·
Replies
6
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
Replies
8
Views
2K
  • · Replies 3 ·
Replies
3
Views
2K