I need to write a program in C++ where the user can do some computation, and when the computation is done, the program will ask the user if he wants to do another computation. I know how to write this in Python:
more = "y"
while (more == "y"):
// computation code
print "Do you want to do another computation? y/n "
more = input()
I created a char variable and used it in the head of the loop, but I don't know how to implement the "input" function in C++. I tried using the cin.get(char_variable) function but the program seems to skip it entirely.
You can use a do-while loop, which basically runs the loop at least once. It runs, then checks the conditional, unlike the plain while loop which checks the conditional then runs. Example:
bool playAgain; //conditional of the do-while loop
char more; //Choice to play again: 'y' or 'n'
string input; /*In this example program, they enter
their name, and it outputs "Hello, name" */
do{
//input/output
cout << "Enter your name: ";
cin >> input;
cout << "Hello, " << input << endl << endl;
//play again input
cout << "Do you want to play again?(y/n): ";
cin >> more;
cout << endl;
//Sets bool playAgain to either true or false depending on their choice
if (more == 'y')
playAgain = true;
else if (more == 'n')
playAgain = false;
//You can add validation here as well (if they enter something else)
} while (playAgain == true); //if they want to play again then run the loop again
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With