getline()即使在clear()之后也会先跳过 [英] getline() skipping first even after clear()
问题描述
所以我有一个函数,可以不断跳过第一个getline,直接跳到第二个.我试图清除缓冲区,但仍然没有运气,这是怎么回事?
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?
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
}
推荐答案
请确保您未使用cin >> str
.在调用函数之前.如果您使用cin >> str
然后又想使用getline(cin, str)
,则必须先调用cin.ignore()
.
Make sure you didn't use cin >> str
. before calling the function. If you use cin >> str
and then want to use getline(cin, str)
, you must call cin.ignore()
before.
string str;
cin >> str;
cin.ignore(); // ignores \n that cin >> str has lefted (if user pressed enter key)
getline(cin, str);
如果使用c字符串:
char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);
ADD :您的错误可能不在于函数本身,而在于之前调用函数.流cin
必须仅在第一个cin.getline
中读取换行符\n'
.
ADD: Your wrong is not probably in the function itself, but rather before calling the function. The stream cin
have to read only a new line character \n'
in first cin.getline
.
这篇关于getline()即使在clear()之后也会先跳过的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!