【问题标题】:mixing cin and getline input issues [duplicate]混合cin和getline输入问题[重复]
【发布时间】:2015-10-24 09:25:00
【问题描述】:

我正在从 C++ 入门中做练习,并尝试做一个程序来接收作为输入的单词和一行。如果当我要求输入一个单词(使用 cin)时,我按下回车键,那么程序将跳过下一行并且不要求输入一行(使用 getline)......如果我在 cin 中写下整个短语(例如“ hello beautifull world") 然后第一个单词 ("hello") 被 cin 捕获,其他两个单词 ("beautifull world") 被 getline 捕获。

我知道在 cin 中,当我输入一个空格时,它会切断输入。我不明白的是两件事:

1.- 为什么如果我用 enter 结束输入(在 cin 中)它会跳过所有其余代码? (有解决办法吗?)

2.- 为什么如果我在 cin 中写一个完整的短语,它会在执行之前将另外两个单词分配给 getline cout

谢谢!对不起我的英语C:

 #include <iostream>
 #include <string>
 using namespace std;

 int main() {

string word, line;

cout << "enter a word" << endl;
cin >> word;

cout << "enter a line" << endl;
getline(cin, line);

cout << "your word is " << word << endl;
cout << "your line is " << line << endl;

return 0;
}

【问题讨论】:

    标签: c++ string getline


    【解决方案1】:

    您需要在两个输入之间使用 cin.ignore():因为您需要将换行符从缓冲区中刷新。

    #include <iostream>
    
    using namespace std;
    
    int main() {
    
    string word, line;
    
    
    cout << "enter a word" << endl;
    cin >> word;
    
    cout << "enter a line" << endl;
    
    cin.ignore();
    getline(cin,line);
    
    cout << "your word is " << word << endl;
    cout << "your line is " << line << endl;
    
    return 0;
    }
    

    对于你的第二个答案,当你在第一个 cin 中输入整个字符串时,它只需要一个单词,其余的由 getline 获取,因此你的程序将在不从 getline 获取输入的情况下执行

    Demo

    【讨论】:

    • Thx!,我认为使用不同的字符串没有必要做这样的事情......我可以假设发生的事情就像 cin 保存信息并阻止输入到其他字符串?最好只使用其中一个(cin 还是 getline?)
    • 这可能有助于消除您的疑虑.. stackoverflow.com/questions/4745858/stdcin-getline-vs-stdcin
    猜你喜欢
    • 2016-01-13
    • 2016-02-05
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    相关资源
    最近更新 更多