Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loops in C++ (while)

Tags:

c++

python

loops

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.

like image 789
rock_crusher Avatar asked Dec 07 '25 01:12

rock_crusher


1 Answers

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
like image 117
Archie Gertsman Avatar answered Dec 08 '25 15:12

Archie Gertsman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!