Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this a bug with getline(), or am I doing something wrong. Right way to use getline()?

Tags:

c++

istream

It might not be a bug, but I don't know what is going wrong. My first entry is repeated for str1 on 2nd iteration, and is same way from then. Only first iteration goes good.

#include <iostream>
#include <string>
using namespace std;

int main () {

cout << " \n Enter two words. \n " ;
char c = 'y';
string str;
string str1;
while (c == 'y'){

    getline(cin,str);

    getline (cin,str1);

    cout << " \n\n str : " << str << " str1 : " << str1 ;
    cout << " \n Continue ? \n " ;
    cin >> c;
}

return 0;
}

The output is :

 Enter two words.
 hello world
this is mr


 str : hello world str1 : this is mr
 Continue ?
 y
hello world


 str :  str1 : hello world
 Continue ?
 n


like image 895
ani Avatar asked Oct 08 '22 11:10

ani


1 Answers

Add

cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

after your

cin >> c;

Consider the following input:

    dog
    cat
    y
    owl
    fish
    n

If we examine the characters that are present in the input stream individually, we'll see:

    d o g \n c a t \n y \n o w l \n f i s h \n n \n

The first call to getline consumes dog\n; the second consumes cat\n, leaving this:

    y \n o w l \n f i s h \n n \n

The first call to cin >> c consumes only y but not the subsequent newline, leaving this:

    \n o w l \n f i s h \n n \n

Now, the fun begins: What happens during the next call to getline? Why it reads up to the next newline, of course. So the next call to getline returns an empty line, and leaves owl... in the input stream.

The solution, as I outlined above, is to consume the remainder of the (now useless) input line.

like image 176
Robᵩ Avatar answered Oct 20 '22 01:10

Robᵩ