-
Question About Getline
Hi,
I've been programming some examples out of a book and I've noticed something about getline that's made me curious. In the following simple program, you enter a make and model of a car, and then it outputs it.
But say you change the line "cin.getline(make, 19);" to "cin.getline(make, 3);". Then, if you enter something like "ford" or anything longer than that, the program no longer asks you the second question. How come?
Code:
#include <iostream>
using namespace std;
char model[20];
char make[20];
int main()
{
cout << "Enter make: ";
cin.getline(make, 19);
cout << "Enter model: ";
cin.getline(model, 19);
cout << make << " " << model;
return 0;
}
Thanks.
-
Because there are still characters in the input buffer since the first cin.getline() call did not read everything. The characters that are left over get assigned to model.
-
Actually not. When the line is longer the stream goes into a failed state.
For this reason getline with C style strings is hard to use (I've never used it in practice). Use std::string, its version of getline and you won't have these worries:
Code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string make, model;
cout << "Enter make: ";
getline(cin, make);
cout << "Enter model: ";
getline(cin, model);
cout << make << " " << model;
return 0;
}