我的问题是:
Ifstream只给我16个元素
您好,在我的c ++代码中,我有多个课程。它们是:
- 数据(包括一些数字)
-Towns(包括至少2个 Data - 对象(在向量中)和状态名称)
-County(管理 Town - 对象)
程序应该使用给定文件的数据填充 Town 对象。
代码如下:
COUNTRY.CPP:
Country::Country(string file) {
ifstream x(file);
Town t;
while (x.good()) {
x >> t;
this->towns.push_back(t);
}
}
更深入 - > “>> “看起来像这样:
TOWN.CPP:
istream& operator>>(std::istream& is, Town& d) {
is >> d.state>> d.town;
Data a, b;
a.SetYear(2011);
is >> a >> b;
// Some other code was here - but i think it's not relevant
return is;
}
更深入 - > “>> “看起来像这样:
DATA.CPP:
istream& operator>>(std::istream& is, Data& d) {
return is >> d.total >> d.male >> d.female;
}
如你所见 - 城镇在一个给定的档案中。文件中的结构一遍又一遍地重复(总共:11292),看起来像这样:
SOURCE(例如)
Baden-Württemberg
Kirchheim am Neckar
5225
2588
2637
5205
2608
2597
Baden-Württemberg
Kornwestheim
31053
15167
15886
31539
15502
16037
第1行:国家
第二行:镇
第3至第5和第6至第8行:数据
REPEAT 的
soo ......由于某种原因,ifstream只给了我16个元素(16个城镇)。嗯....
答案 0 :(得分:2)
使用shift运算符读取std::string
只读一个单词。默认情况下,单词由空格分隔。结果,字符串Kirchheim am Neckar
将不会被完全读取,但只会读取Kirchheim
。当尝试将am
作为整数读取时,流将进入失败模式并拒绝读取任何内容,直到其标志为clear()
为止。
您可能希望通过阅读完整的行来阅读城镇和可能的州。使用std::getline(stream, str)
执行此操作。此外,始终测试读取尝试后读取操作 的成功。使用流的惯用方法是
while (x >> t) {
...
}