简体   繁体   中英

getline ignores first character of string input

Why does C++'s getline function ignore the first character of my input?

In this post , the culprit was cin.ignore() , but I don't have the cin.ignore() function in my code.

Here's a very basic sample of what I'm trying to do:

#include <iostream>
#include <string>

using namespace std;

int main(){

    string user_input;

    cout << "input: ";
    cin >> user_input;
    getline(cin,user_input);

    cout << "length: " << user_input.length() << endl;
    cout << "your input: " << user_input << endl;

    return 0;
}

The problem is, the output is totally wrong:

input: 1 2 3
length: 4
your input:  2 3

Obviously the length of the string, with spaces included, should be 5 , not 4 . You can also see that the 1st character of user_input is missing.

Can somebody explain to me why this code gives the wrong output and what I need to do to fix this problem? I've never worked with strings that contain spaces like this. I'm curious about what causes this problem to arise: :)

cin >> user_input is the culprit. It's grabbing the input until the first space Get rid of that line of code and you should be all set with just the getline(cin,user_input) .

cin >> user_input;

I'm not sure why you put that line there, but that reads and consumes the first space delimited string from cin . So it reads the 1. After that, getline reads the rest of the line, which is " 2 3" .

cin >> user_input; is eating the first number. Then getline() comes along and gets the rest of the input. Remove cin >> user_input; and it should work fine.

just remove this line cin >> user_input; then your code will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM