如何将用户输入限制为某些字符串值? 对不起,如果这是一个简单的问题,但我对C++是相当新的。我写的任何方式都是简单的气象站,它接收用户输入并最终打印出来。在这种特定情况下,要求用户输入风向,并使用给定的N、NE、NW……等选项。我的问题是,我可以有一些循环,如果他们没有输入那些适当的字符串值,它会显示“无效重试”,并重新执行该过程

如何将用户输入限制为某些字符串值? 对不起,如果这是一个简单的问题,但我对C++是相当新的。我写的任何方式都是简单的气象站,它接收用户输入并最终打印出来。在这种特定情况下,要求用户输入风向,并使用给定的N、NE、NW……等选项。我的问题是,我可以有一些循环,如果他们没有输入那些适当的字符串值,它会显示“无效重试”,并重新执行该过程,c++,loops,C++,Loops,代码如下: //Asks the user to input the current wind direction and stores it as windDirection cout << "Please enter the current wind direction(N, NE, NW, S, SE, SW, E, W), then press enter." << endl; getline(cin, windDirection

代码如下:

    //Asks the user to input the current wind direction and stores it as    windDirection

    cout << "Please enter the current wind direction(N, NE, NW, S, SE, SW, E, W), then press enter." << endl;

    getline(cin, windDirection);
//要求用户输入当前风向并将其存储为windDirection

cout这个while循环最终为我工作,感谢那些帮助我的人。它可能会更好,但它做的工作

    //Asks the user to input the current wind direction and stores it as windDirection
    while (cout << "Please enter the current wind direction(N, NE, NW, S, SE, SW, E, W), then press enter." << endl &&
                cin >> windDirection && windDirection != "N" && windDirection != "NE" && windDirection != "NW" && windDirection != "S"
                && windDirection != "SE" && windDirection != "SW" && windDirection != "E" && windDirection != "W"){

     cout << "That is an Invalid wind direction input, try again.\n";
     cin.clear(); 
     cin.ignore();
            }
//要求用户输入当前风向并将其存储为windDirection
而(cout windirection&&windirection!=“N”&&windirection!=“NE”&&windirection!=“NW”&&windirection!=“S”
&&风向!=“SE”&&windDirection!=“SW”&&windDirection!=“E”&&windDirection!=“W”){

难道答案是“是的”。使用
while
循环,直到您获得有效的输入。或者,这个问题是为您编写代码的一个微妙建议吗?@PCLuddite不是真的,我很好奇,因为我做了一个我认为是不错的while循环尝试,但没有成功,所以不确定是否可能。@Christian最好展示您的尝试。这样我们可以帮助您rect它。@PCLuddite我实际上刚刚得到了我发布到工作中的while循环!