C ++无意义的表达填充

时间:2014-04-15 19:44:24

标签: c++ visual-c++ while-loop expression conditional-statements

我在VS 2013 Express(适用于Windows桌面)中为控制台应用程序提供了这个简单的c ++程序:

#include <iostream>
#include <string>
using namespace std;

int main()
{
string mystr;
cout << "Welcome, what is your name? ";
getline(cin, mystr);
cout << "Nice to meet you, " << mystr << endl;
cout << "May i call you \"Idiot\" for short? (y/n)" << endl;

string mystr2;
getline(cin, mystr2);

while ( ??? ) 
{
    if (cin)
    {
        if (mystr2 == "y")
        {
            cout << "Thank you, Idiot" << endl;
        }
        else
        {
            if (mystr2 == mystr)
            {
                cout << "You found the hidden secret! The hidden secret is..... I dunno. It is what ever you want it to be. \n \nProbably a let down." << endl;
            }
            else
            {
                if (mystr2 == "n")
                {
                    cout << "Ok then, " << mystr << endl;
                }
                else
                {
                    cout << "Please enter a valid response (y/n)" << endl;
                    getline(cin, mystr2);
                }
            }
        }
    }
}

}

我刚刚开始学习,我更喜欢学习,因为我做了一些事情,所以我决定这样做。正如您可能从最后的其他声明中猜到的那样,我希望它说'#34;请输入有效的回复(y / n)&#34;如果用户输入了除y,n或mystr2 == mystr之外的任何内容。它工作正常但我需要循环所以我把它全部放在while语句中。

我现在需要一个不会影响它的while语句的表达式,或者是用户触发最后一个else语句的结果。这个填充物是我需要帮助的。

我知道它很小而且没有意义,但我想完成它。

4 个答案:

答案 0 :(得分:3)

getline返回对其正在读取的流的引用。并且所有流都提供对bool的隐式转换,如果流有效(即如果上一次操作成功),则会导致true。所以这样做非常惯用:

string mystr2;

while (getline(cin, mystr2))
{
    if (mystr2 == "y")
    {
        cout << "Thank you, Idiot" << endl;
    }
    else
    {
        if (mystr2 == mystr)
        {
            cout << "You found the hidden secret! The hidden secret is..... I dunno. It is what ever you want it to be. \n \nProbably a let down." << endl;
        }
        else
        {
            if (mystr2 == "n")
            {
                cout << "Ok then, " << mystr << endl;
            }
            else
            {
                cout << "Please enter a valid response (y/n)" << endl;
            }
        }
    }
}

答案 1 :(得分:1)

我认为您正在寻找while(true),这只是一个无限循环,直到您breakreturn为止。它不会影响你的任何其他事情。

答案 2 :(得分:1)

您可以简单地使用while(true)来循环执行无限期。如果您希望停止,则必须breakreturn

答案 3 :(得分:1)

我想你想要while(mystr2!="y" && mystr2!="n" && mystr2!=mystr) 这样,如果输入不是&#34; y&#34;,&#34; n&#34;或mystr,它将继续循环。