在使用cin后使用getline(cin, s)的方法

49
我需要下面的程序获取用户输入的整行并将其放入字符串names中:
cout << "Enter the number: ";
int number;
cin >> number;

cout << "Enter names: ";
string names;

getline(cin, names);

getline()命令之前使用cin >> number命令(我猜这就是问题所在),它将不允许我输入名称。为什么?

我听说过cin.clear()命令,但我不知道它的作用是什么,也不知道为什么需要使用它。


23
假设您输入了:5<Enter>John<Enter>。然后,cin >> number 只读取了数字 5,而将换行符(Enter)留在流中。因此,当尝试使用 getline(cin,name) 读取名称时,它会一直读到行末。但请注意,这里有一个换行符准备好被读取(因此名称将为空(因为您没有在读取数字 5 后读取掉换行符)。如果您想在 >> 和 getline() 之间切换,则需要小心处理输入的末尾换行符。 - Martin York
@LokiAstari: 这是比下面所有回答都更好的_答案_。你能把它发表为这样的答案吗? - Lightness Races in Orbit
13个回答

0

在你的 cin 语句之后使用 cin.ignore(),因为你想忽略掉从 cin 中获取 int 变量后剩余在缓冲区中的 "\n"。

我有一个类似的程序,也遇到了类似的问题:

#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;

int main() {
    int i = 4;
    double d = 4.0;
    string s = "HackerRank ";

    // Declare second integer, double, and String variables.
    int n;
    double d2;
    string str;

    // Read and save an integer, double, and String to your variables.
    cin >> n;
    cin >> d2;

    cin.ignore();

    getline(cin, str);

    // Print the sum of both integer variables on a new line.
    cout << i + n << endl;


    // Print the sum of the double variables on a new line.
    cout << d + d2 << endl;

    // Concatenate and print the String variables on a new line
    cout << s << str << endl;

    // The 's' variable above should be printed first.

    return 0;
}

0

你可以在cppreference中找到你想要的答案。

当紧跟着以空格为分隔符的输入后使用时,例如在 int n; std::cin >> n; 之后,getline会消耗掉由operator>>留在输入流中的换行符,并立即返回。一个常见的解决方案是在切换到基于行的输入之前,使用 cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 忽略输入行上所有剩余的字符。


-1
#include <iostream>
#include <string>

using namespace std;

int main()
{
    cout << "Enter the number: ";
    int number;
    cin >> number;
    cout << "Enter names: ";
    string names;

    // USE peek() TO SOLVE IT! ;)
    if (cin.peek() == '\n') {
        cin.ignore(1 /*numeric_limits<streamsize>::max()*/, '\n');
    }

    getline(cin, names);

    return 0;
}

只需使用 cin.peek() 预览一下,看看 cin 的内部缓冲区是否还剩下一个 '\n'。如果是这样:忽略它(基本上跳过它)


如果是'\r'怎么办?这个解决方案非常脆弱,我会在代码审查中拒绝它。 - Lightness Races in Orbit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接