我需要用C++编写一个程序,用户可以在其中进行一些计算,计算完成后,该程序将询问用户是否要进行其他计算。我知道如何用Python编写此代码:

more = "y"
while (more == "y"):
    // computation code
    print "Do you want to do another computation? y/n "
    more = input()

我创建了一个char变量并在循环的开头使用了它,但是我不知道如何在C++中实现“输入”功能。我尝试使用cin.get(char_variable)函数,但该程序似乎完全跳过了它。

最佳答案

您可以使用do-while循环,该循环基本上至少运行一次循环。它先运行然后检查条件,这与普通的while循环不同,后者检查条件然后运行。例子:

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

09-10 03:54
查看更多