如何强制 getline() 一次输入一行

How to force getline() to input one line at a time

本文关键字:输入 一行 一次 何强制 getline      更新时间:2023-10-16

我需要输入一定数量的字符串,每个字符串都在新行上输入。当我尝试在循环中使用 getline() 时,它会输入第一个字符串,然后立即结束。

这是我试图解决的问题,您可以在其中看到我要的输入样式:https://wcipeg.com/problem/ccc98s1

我已经查看了cin.ignore()来解决问题,但我似乎无法使其正常工作。

int n;
cin >> n;
for(int i = 0; i < n; i++) {
    string input;
    getline(cin, input);
    cout << "Line Entered: " << input << endl;
}

如果您输入 2 表示 n,然后尝试在单独的行上输入两个字符串,则它不起作用。

int n;
cin >> n;
cin.ignore(); // are you sure you tried this?
for(int i = 0; i < n; i++) {
    string input;
    getline(cin, input);
    cout << "Line Entered: " << input << endl;
}