c++ - 如何阻止程序跳过 getline?

标签 c++ input getline

<分区>

这是我的主程序,

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";
    }
}

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

输入名字:输入姓氏:

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

最佳答案

string command;
cin>>command;

在这之后只吃掉行尾

string restOfLine;
getline(cin, restOfLine);

否则,您输入命令的行中的 '\n' 不会被消耗,下一个读取行将只读取它。

关于c++ - 如何阻止程序跳过 getline?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4067256/

相关文章:

c++ - 为什么在这种情况下模板参数是引用?

c++ - 抽象和纯虚拟方法

variables - 接受用户对变量的输入

c++ - 用户输入...如何检查 ENTER 键

c++ - 当我们尝试使用 istream::getline() 和 std::getline() 提取文件中出现 `eof` 字符的行时,实际会发生什么

c++ - cin.getline 跳过一行输入并获取下一行

c++ - 有没有办法比较 Visual Studio 中的 obj 文件?

c++ - 在调用 C 函数的其他不抛出内联函数上添加 noexcept?

javascript - 如何使用 javascript 值设置 HTML 输入字段的值

JavaScript 函数难度