3

In this answer I have the following code:

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <iterator>
#include <limits>

using namespace std;

struct station{
    string _stationName;
    int _studentPass;
    int _adultPass;
};

std::istream& operator>>(std::istream& is, station& rhs){
    getline(is, rhs._stationName, ';');
    is >> rhs._studentPass >> rhs._adultPass;
    return is;
}

int main(){
    istringstream foo("4;\nSpadina;76 156\nBathurst;121 291\nKeele;70 61\nBay;158 158");

    foo.ignore(numeric_limits<streamsize>::max(), '\n');

    vector<station> bar{ istream_iterator<station>(foo), istream_iterator<station>() };

    for (auto& i : bar){
        cout << i._stationName << ' ' << i._studentPass << ' ' << i._adultPass << endl;
    }

    return 0;
}

It's output is:

Spadina 76 156

Bathurst 121 291

Keele 70 61

Bay 158 158

My expected output does not double space:

Spadina 76 156
Bathurst 121 291
Keele 70 61
Bay 158 158

I get the expected output if I change my operator>> to:

std::istream& operator>>(std::istream& is, station& rhs){
    if (is >> rhs._stationName >> rhs._adultPass){
        auto i = rhs._stationName.find(';');

        rhs._studentPass = stoi(rhs._stationName.substr(i + 1));
        rhs._stationName.resize(i);
    }
    return is;
}

This seems like a compiler bug or something, but that would be strange cause I'm seeing this behavior in both Visual Studio 2013 and gcc 4.9.2.

Can anyone explain this to me?

4

1 回答 1

5

operator >>返回int不会丢弃它之后的空格,因此当_adultPass被读取时,流中的下一个字符是\n. 如果您随后在getline处停止运行,';'则还会读取此换行符并将其存储在字符串的开头。

于 2015-02-13T12:36:26.220 回答