C++中的循环(while)

3

我需要用C++编写一个程序,用户可以进行一些计算,当计算完成后,程序会询问用户是否想进行另一次计算。我知道如何在Python中编写这个程序:

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

我创建了一个字符变量并在循环的头部使用它,但是我不知道如何在C++中实现"input"函数。我尝试使用cin.get(char_variable)函数,但程序似乎完全跳过了它。


Python在标记方面有什么作用? - user2118542
5个回答

4
您可以使用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

3

您可以使用cin >> char_variable;来获取这个值。
不要忘记:

#include <iostream>
using namespace std;

1
如果您使用了cin.get,可能会遇到以下问题。如果运行此代码:
cout << "give a number:";
int n;
cin >> n;
cout << "give a char:";
char c;
cin.get(c);
cout << "number=" << n << endl;

你会得到这种情况。
give a number:12
give a char:number=12

在这里看起来 cin.get() 被忽略了。实际上并不是这样。它读取了你在数字后键入的“行末标志”。如果你添加一些代码,就可以看到它。

cout << "char code=" << (int) c << endl;

查看字符的数字值。

--- 最好使用 cin >> c;,因为它会等待第一个非空白字符。


1
我是这样写的。我使用了 cin 来获取用户输入的 char 值。
#include <iostream>
using namespace std ;
int main ()
{
    char more;
    cout<<"Do you want to do another computation? y/n ";
    cin>>more;
    while(more=='y'){
        cout<<"Do you want to do another computation? y/n ";
        cin>>more;
    }
}

0
你的程序非常简单和易懂。它像这样:-
#include <iostream>
using namespace std;
int main()
{
    char ch='y';
    do
    {
        // compute....
        cout<<"do you want to continue ?: "<<flush;
        cin>>ch;
    }while (ch=='y' || ch=='Y');   // don't for get the semicolon
    return 0;
}

如果你想使用while循环而不是do while循环,你的代码将会是:

#include <iostream>
using namespace std;
int main()
{
    char ch='y';
    while (ch=='y' || ch=='Y')
    {
        // compute....
        cout<<"do you want to continue ?: "<<flush;
        cin>>ch;
    }    // no semicolon needed as in `do while`
    return 0;
}

简单!希望你的代码能够正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接