首页 文章

在C中,如果按下返回键,如何使cin“取消”?

提问于
浏览
0

我正在尝试通过编写一个简单的控制台应用程序来学习C语言 . 用户通过输入存储在变量中的数字来导航主菜单,然后switch语句用它来确定要做什么 . 这很简单 . :)

困扰我的问题是,当程序到达cin语句时,按下return而不输入数字不会“退出”语句,而只是将其压缩到下一行 . 我想这是有道理的,但我怎么能让它如此紧迫,没有先前的输入只是“退出”或“取消”cin声明?

下面简要介绍了我的应用程序的样子:

int main()
{
    int mainMenuSelector;

    while(mainMenuSelector != 4){
        cout << "--- MAIN MENU -----------------" << endl;
        cout << "[1] First Option" << endl;
        cout << "[2] Second Option" << endl;
        cout << "[3] Third Option" << endl;
        cout << "[4] Exit Application" << endl;
        cout << "-------------------------------" << endl;
        cout << "Selection: ";

        cin >> mainMenuSelector;
        // This is the statement I want to move along from
        // if the user presses the return key without entering any input.

        switch(mainMenuSelector){
            case 1:
                doSomething();
                break;
            case 1:
                doSomething();
                break;
            case 2:
                doSomething();
                break;
            case 3:
                doSomething();
                break;
        }
    }
    return 0;
}

3 回答

  • 3
    std::string input;
    while (std::getline(std::cin, input) && !input.empty()) { /* do stuff here */ }
    

    您可能想要进一步验证输入是否有效,是否只有一堆空格等...

  • 1

    在没有输入的情况下按Enter键会产生空字符串值 . 你可以这样做(尝试并使其适应你的代码):

    #include <string>
    #include <iostream>
    using namespace std;
    
    int main() {
        string s;
        getline(cin, s);
        while(s != "") { // if the person hits enter, s == "" and leave the loop
            cout << s << endl;
            getline(cin, s);
        }
        return 0;
    }
    
  • 1

    如果您专门寻找使用流操作符的选项(而不是自己解析输入),您可以考虑使用std :: stringstream . 例如:

    #include <string>
    #include <iostream>
    #include <sstream>
    
    using namespace std;
    
    void ExampleCaptureInput()
    {
        int value;
        string s;
        getline(cin, s);
        if (s != "")
        {
            stringstream sstream(s);
            sstream >> value;
        }
    }
    

相关问题