C++ 即使在 clear() 之后, getline() 也会先跳过

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12186568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 15:58:54  来源:igfitidea点击:

getline() skipping first even after clear()

c++arrayscharbuffergetline

提问by Derp

So I have a function that keeps skipping over the first getline and straight to the second one. I tried to clear the buffer but still no luck, what's going on?

所以我有一个函数可以不断跳过第一个 getline 并直接跳到第二个。我试图清除缓冲区但仍然没有运气,这是怎么回事?

void getData(char* strA, char* strB)
{
    cout << "Enter String 1: ";               // Shows this line
    cin.clear();
    cin.getline(strA, 50);                    // 50 is the character limit, Skipping Input

    cout << endl << "Enter String 2: ";       // Showing This Line
    cin.clear();
    cin.getline(strB, 50);                   // Jumps Straight to this line
}

回答by

Make sure you didn't use cin >> str. before calling the function. If you use cin >> strand then want to use getline(cin, str), you must call cin.ignore()before.

确保你没有使用cin >> str. 在调用函数之前。如果您使用cin >> str然后想使用getline(cin, str),则必须先调用cin.ignore()

string str;
cin >> str;
cin.ignore(); // ignores \n that cin >> str has lefted (if user pressed enter key)
getline(cin, str);

In case of using c-strings:

如果使用 c 字符串:

char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);

ADD: Your wrong is not probably in the function itself, but rather beforecalling the function. The stream cinhave to read only a new line character \n'in first cin.getline.

ADD:您的错误可能不在于函数本身,而在于调用函数之前。流cin必须\n'在 first 中只读取一个换行符cin.getline

回答by Michael Burr

cin.clear();clears any error bits on the stream - it does not consume any data that may be pending.

cin.clear();清除流上的任何错误位 - 它不会消耗任何可能挂起的数据。

You want to use cin.ignore()to consume data from the stream.

您想使用它cin.ignore()来消费流中的数据。

回答by Sukeshini

use cin.ignore(-1);It will not remove the first character of the input string

使用cin.ignore(-1);它不会删除输入字符串的第一个字符

回答by Krzychu8

After you read something there is still 'RETURN' character inside bufor so you have to cin.ignore()after each read.

阅读完内容cin.ignore()后,bufor 中仍然有“返回”字符,因此每次阅读后都必须这样做。

You can also use cin.sync()to clear the stream. Actualy clear method only clears flags.

您也可以使用cin.sync()来清除流。实际上 clear 方法只清除标志。

There is also option that you can go to the end of stream, with nothing left to read you should write without problems.

还有一个选项,您可以转到流的末尾,没有任何可阅读的内容,您应该毫无问题地编写。

std::cin.seekg(0, std::ios::end);

It is up to you what will you use.

您将使用什么取决于您。