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 eating the first number. Then getline()
comes along and gets the rest of the input. Remove cin >> user_input;
and it should work fine.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With