Jon*_*Mee 3 c++ cout line-breaks extraction-operator c++11
在这个答案中,我有以下代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
它的输出是:
Spadina 76 156
Bathurst 121 291
Keele 70 61
Bay 158 158
我的预期产量不会增加一倍:
Spadina 76 156
Bathurst 121 291
Keele 70 61
Bay 158 158
如果我将我operator>>改为:我得到预期的输出:
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;
}
Run Code Online (Sandbox Code Playgroud)
这似乎是一个编译器错误或其他东西,但这很奇怪,因为我在Visual Studio 2013 和 gcc 4.9.2 中都看到了这种行为.
任何人都可以向我解释这个吗?
operator >>返回后int不会丢弃空格,所以当_adultPass读取时,流中的下一个字符是\n.如果再运行getline停在';'这换行符被读取,以及和存储在字符串的开头.
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |