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

我只是一个虾纸丫 提交于 2019-12-01 06:07:44

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.

As rob says.

But an alternative fix that looks nicer:

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

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

When dealing with manual user input you should be careful of using the >> operator as this will always leave the '\n' on the input. Which means you can either use a method that retrieves the '\n' character (getline()) or you can manually remove it afterwords (ignore()).

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!