如何让我的终端在 C++ 中的空 cin 输入上退出?

问题描述 投票:0回答:1

我找不到一种方法让我的终端在空输入时退出程序。我有:

int main(int argc, char const* argv[]) {
    // Write your code here
    // Define variables

    set<string> words;  // The set
    bool more = true;     //  Flag indicating there are more lines to read

    // If there is no command line argument, use stdin to get the lines
    if (argc == 1){

        // Take lines in until a blank line is entered
        while (more) {

            // Get next line from stdin
            string input;
            cin >> input;

                // Quit if we hit a blank line
                if (input.empty() ) {
                    more = false;
                    break;
                }

我已经尝试过:

if (!cin )
if (input == "")
if (input == "\n")
if (input == "" || "\n")
if (input.empty())

对于每一个,我希望程序不接受任何输入,或者简单地按回车键,作为接受输入的结束并退出。

c++ terminal stdstring is-empty
1个回答
1
投票

使用

std::getline
逐行阅读。如果该行为空,则用户只需按 Enter

使用

>>
,您需要在按Enter之前输入一些非空格字符。

另请注意,您当前的输入只会读取单个空格分隔的“单词”,而不是一行。要阅读一行,您确实需要

std::getline

© www.soinside.com 2019 - 2024. All rights reserved.