简体   繁体   中英

What is this cin.getline() behaviour?

I'm not looking for alternatives just trying to understand why C++ does this.

char name[25];

cin.getline(name, 25);

If for example I go over the getline's '25' input limit, why does it do it but rush through the program, it doesn't stop for any cin.get(), does it have to do with a failbit flag?

#include <iostream>
#include <cstring> // for the strlen() function

using namespace std;

int main()
{

char defName[25];
char name[25];

for (int x = 0; x < 25; x++)
{
    if (x != 24)
    defName[x] = 'x';
    else
    defName[x] = '\0';
}



cout << "Default Name: " << defName << endl << endl;

cout << "Please enter a name to feed into the placeholder (24 Char max): ";

cin.getline(name, 25);

name[24] = '\0';

cout << "You typed " << name << endl;
cin.get();

for (int i = 0; i < strlen(name); i++)
    if (name[i] != ' ')
    {
{
    defName[i] = name[i];
}
    }


cout << "Placeholder: " << defName;

    cin.get();
return 0;
}

does it have to do with a failbit flag?

Indeed, failbit is set if the input is too long for the buffer. You can check for this:

if (!cin.getline(name, 25)) {
    cout << "Too long!\n";
}

and, if you want to carry on, clear it with cin.clear() , and remove the unread characters with cin.ignore(-1) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM