在 C++ 中使用 cin.getline() 后不从键盘获取输入

Not taking Input from keyboard after using cin.getline() in C++

在下面的程序中,当我输入长度小于或等于10的字符串时它可以正常工作但是当我超过字符串长度时,getline可以正常工作但后续的输入语句将不起作用(不接受输入) /* 使用正确 header */

int main () 
{
int a,b;
char s[10];
cin>>a;  //work fine
cin.ignore(); 
cin.getline(s,10); // work fine but if the length of string is more than 10...

cin>>b;  //...this line doesn't work
cout<<"a="<<a<<"s="<<s<<" b="<<b;
getch();
}

这是您的解决方案:

#include <climits>
#include <iostream>
using namespace std;

int main() {
    int  a, b;
    char s[11]; // <-- Size should be 11, the last character will be '[=10=]'
    cin >> a;
    cin.ignore(); // better change it to cin.ignore(numeric_limits<streamsize>::max(), '\n');
    cin.getline(s, 11); // <-- this line sets failbit if the input exceeds 10 characters

    // add these lines :
    if (!cin) { // <-- checks if failbit is set
        cin.clear(); // <-- clears the set flags
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); // <-- ignores the whole line
    }
    // if anything had gone bad, it has been fixed by now

    cin >> b;
    cout << "a = " << a << "\ns = " << s << "\nb = " << b;
}


一个更复杂但更好的:

#include <climits>
#include <iostream>
using namespace std;

int main () 
{
    cin.exceptions(ios_base::failbit|ios_base::badbit); // <-- tells compiler to treat failbit and badbit as exceptions
    int a, b;
    char s[11];
    cin >> a;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    try {
        cin.getline(s, 11);
    } catch (ios_base::failure &e) {
        // cerr << e.what() << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    cin >> b;
    cout << "a = " << a << "\ns = " << s << "\nb = " << b;
}

简单的解决方案,改用scanf("%[^\n]",s)

It reads a whole line into an array until you press Enter key. You can modify it as you want. Just replace ‘\n’ with the character you want to be the end of the input.

您的情况如下:

    int main () {

        int a,b;
        char s[10];

        cin>>a; 
        cin.ignore(); 
        scanf("%[^\n]",s);
        cin>>b;      

        cout<<"a="<<a<<"s="<<s<<" b="<<b;

        return 0;

    }