getline()甚至在clear()之后跳过

Der*_*erp 10 c++ arrays buffer char getline

所以我有一个功能,一直跳过第一个getline,直接跳到第二个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
}
Run Code Online (Sandbox Code Playgroud)

小智 16

确保你没有使用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);
Run Code Online (Sandbox Code Playgroud)

如果使用c字符串:

char buff[50];
cin.get(buff, 50, ' ');
cin.ignore();
cin.getline(buff, 50);
Run Code Online (Sandbox Code Playgroud)

ADD:您的错误可能不在函数本身,而是调用函数之前.流cin有只读换行符\n'在第一cin.getline.