what's the difference between cin.get() and cin.getline()

also suppose I have to arrays or string

like in this code

1
2
3
4
5
6
  char name[20];
char fakename[20];
cout<<"Enter your name\n";
cin.get(name,20); // why does this print my name then let the program stop without asking me for my second name ?
cout<<"second name\n";
cin.get(fakename,20);


read the comment.
cin.get() will grab the input (ignoring leading whitespace) until the first whitespace character, cin.getline() will get the input until the first newline character.

So, if you typed in "Vallius Dax" and hit enter, then your cin.get() at line 4 would grab Vallius, your cin.get() at line 6 would grab Dax and the program would continue.

Try this:
1
2
3
4
5
6
7
8
9
10
11
12
 
#include <string>
.
.
.

string name;
string fakename;
cout<<"Enter your name\n";
getline(cin, name);
cout<<"second name\n";
getline(cin, fakename);
Last edited on
1
2
3
4
5
6
7
char name[20];
char fakename[20];
cout<<"Enter your name\n";
cin.get(name,20); // why does this print my name then let the program stop without asking me for my second name ?
cin.ignore();//<<<<<<<<<<<<<
cout<<"second name\n";
cin.get(fakename,20);
get() method from the istream class reads until it bumped to the new-line character, but does not store it
and it is left in the buffer... then, when second name should be typed, method looks into the buffer if there is something to be taken, a there it is - new-line character from previous reading. And as I mentioned, get() stops reading when '\n' occures, so it looks like second name was skipped, but it just reads '\n' from buffer and stops

Topic archived. No new replies allowed.