<istream> input with both cin and getline

Hey everyone!

I have a member friend function that receives an istream and reads values from it into private attributes of the object:

1
2
3
4
5
6
7
istream &operator>>(istream &is, Object1 &p) {
    is >> p.int1;
    is >> p.int2;
    getline(is, p.string1);

    return is;
}


the file looks like this:

1
2
3
3 5 this is a
4 10 string to
5 20 read and such


If I wanted to read in the first line, I would want p.int1 = 3, p.int2 = 5, and p.string1 = "this is a".

However, I instead get p.string1 = " this is a". I don't want the space in front, but I cannot figure out how to get rid of it. What would be an efficient and readable way to read in the values?

-----------------------------------------------------------------------------------------
Update:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
istream &operator>>(istream &is, Object1&p) {
    string temp;
    is >> p.int1;
    is >> p.int2;
	getline(is, temp);
	if(!temp.empty()) {
		if(temp[0] == ' ') {
			temp = temp.substr(1, temp.length() - 1);
		}
	}
	p.string1= temp;

	return is;
}


This seems to work, but it is messy. Is there a more readable and simpler way to solve this?
Last edited on
1
2
3
4
5
6
7
std::istream &operator>>(std::istream &is, Object1 &p) {
    is >> p.int1;
    is >> p.int2;
    //http://en.cppreference.com/w/cpp/io/manip/ws
    std::getline(is >> std::ws, p.string1);
    return is;
}
I had no idea std::ws existed. This solves my problem. Thank you!
Topic archived. No new replies allowed.