Reputation:
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;
}
Upvotes: 0
Views: 265
Reputation: 254501
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)
.
Upvotes: 2