【问题标题】:How do I stop program from skipping over getline? [duplicate]如何阻止程序跳过 getline? [复制]
【发布时间】:2011-05-03 07:23:33
【问题描述】:

这是我的主程序,

int main () {

    string command;
    cin>>command;

    if(command == "keyword")
    {
        string str, str2, str3, str4;

        cout << "Enter first name: ";
        getline (cin,str);

        cout << "Enter last name: ";
        getline (cin,str2);

        cout << "Enter age: ";
        getline (cin,str3);

        cout<<"Enter country: ";
        getline (cin,str4);

        cout << "Thank you, " << str <<" "<<str2 <<" "<<str3<<" "<<str4<< ".\n";
    }
}

输入关键字后,程序立即输出:

输入名字:输入姓氏:

完全绕过输入名字的能力。

【问题讨论】:

    标签: c++ input getline


    【解决方案1】:
    string command;
    cin>>command;
    

    在这之后就吃线的结尾

    string restOfLine;
    getline(cin, restOfLine);
    

    否则,输入命令的行中的“\n”不会被消耗,下一个 readline 只会读取它。高温

    【讨论】:

    【解决方案2】:

    cin &gt;&gt; command 不会从输入流中提取换行符 ('\n');当您致电getline() 时,它仍然存在。因此,您需要额外调用getline()(或ignore())来处理此问题。

    【讨论】:

      【解决方案3】:

      正如其他人所提到的,问题是在读取命令时,您将行尾字符留在缓冲区中。除了@Armen Tsirunyan 提出的替代方案,您还可以使用其他两种方法:

      • 为此使用std::istream::ignorecin.ignore( 1024, '\n' );(假设行的宽度不会超过 1024 个字符。

      • 只需将cin &gt;&gt; command 替换为getline( cin, command )

      这两种方法都不需要创建额外的字符串,第一种方法较弱(如果行很长),第二种方法修改了语义,因为现在整个第一行(不仅仅是第一个单词)都作为命令处理,但这可能没问题,因为它允许您执行更严格的输入检查(命令在第一个单词中按要求拼写,并且命令行中没有额外的选项。

      如果您有不同的命令集并且有些可能需要参数,您可以一次读取命令行,然后从那里读取命令和参数:

      std::string commandline;
      std::vector<std::string> parsed_command;
      getline( cin, commandline );
      std::istringstream cmdin( commandline );
      std::copy( std::istream_iterator<std::string>(cmdin), std::istream_iterator(),
                 std::back_inserter( parsed_command ) );
      // Here parsed_command is a vector of word tokens from the first line: 
      // parsed_command[0] is the command, parsed_command[1] ... are the arguments
      

      【讨论】:

        猜你喜欢
        • 2021-11-26
        • 2017-02-13
        • 1970-01-01
        • 2021-11-24
        • 1970-01-01
        • 2014-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多