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

It may not be a mistake, but I do not know what is going wrong. My first entry is repeated for str1 at the 2nd iteration, and at the same speed. Only the first iteration is going well.

#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;
}

Conclusion:

 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


+5
source share
2 answers

Add

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

after

cin >> c;

Consider the following input:

    dog
    cat
    y
    owl
    fish
    n

If we look at the characters that are present individually in the input stream, we will 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 getlineconsumes dog\n; the second consumes cat\n, leaving this:

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

cin >> c y , , :

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

: getline? , . getline owl... .

, , , ( ) .

+3

rob.

, :

// change
char c = 'y';
....
while (c == 'y'){
....
    cin >> c;

// Into
std::string c = "y";
....
while (c == "y"){
....
    std::getline(cin, c);

→ , "\n" . , , "\n" (getline()), (ignore()).

+1

All Articles