+ 2

What getline really do

I want to now why we have to do a cin.clear () between a cin and a getline...

6th Nov 2016, 8:02 PM
Guilamb
Guilamb - avatar
4 Answers
+ 3
You actually need to flush (clean the buffer) between using cin and get line. cin leaves \n in the buffer so get line sees it and stops reading, since it only reads until it sees \n. cin.ignore() is used for that. I don't understand if your input was 2 lol lolipop with or without \n. Both terminal and codeblocks would put 2 in aVariable and end your program.
6th Nov 2016, 9:44 PM
Milica Todorovic
Milica Todorovic - avatar
+ 1
cin only takes what's before first space. For example, if type in Solo Learn, it'll only register Solo and ignore Learn. getline is used when you want the whole line. It will register everything you type in before enter. So if you use getline, Learn won't be ignored.
6th Nov 2016, 9:14 PM
Milica Todorovic
Milica Todorovic - avatar
0
yep but if you do int aVariable; string anotherOne; cin>>aVariable; getline (cin,anotherOne); ________________________ input : 2 lol lolipop _________________________ it will only take the second one (lolipop ). why ?
6th Nov 2016, 9:22 PM
Guilamb
Guilamb - avatar
0
ok thinks
7th Nov 2016, 5:04 PM
Guilamb
Guilamb - avatar