Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getline ignores first character of string input

Tags:

c++

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! :)

like image 311
user2371809 Avatar asked Jun 10 '15 19:06

user2371809


2 Answers

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.

like image 194
NathanOliver Avatar answered Oct 19 '22 07:10

NathanOliver


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".

like image 45
Benjamin Lindley Avatar answered Oct 19 '22 07:10

Benjamin Lindley