【问题标题】:ifstream gives me only 16 elementsifstream 只给了我 16 个元素
【发布时间】:2016-11-20 03:29:34
【问题描述】:

我的问题是:
Ifstream 只给了我 16 个元素

您好,在我的 c++ 代码中,我有多个类。他们是:
-数据(包括一些数字)
- 城镇(包括至少 2 个数据-对象(在一个向量中)和州名)
-县(管理城镇-对象)

程序应该用给定文件的数据填充 Town 对象。 代码如下所示:

COUNTRY.CPP:

Country::Country(string file) {
  ifstream x(file);

  Town t;
  while (x.good()) {
    x >> t;
    this->towns.push_back(t);
  }
}

为了更深入 -> “>> 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;
}

为了更深入 -> „>> a“ 看起来像这样:

DATA.CPP:

istream& operator>>(std::istream& is, Data& d) {
    return is >> d.total >> d.male >> d.female;
}

如您所见 - 城镇位于给定文件中。文件中的结构一遍又一遍地重复(总共:11292),看起来像这样:

来源(示例)

Baden-Württemberg
Kirchheim am Neckar
5225
2588
2637
5205
2608
2597
Baden-Württemberg
Kornwestheim
31053
15167
15886
31539
15502
16037

第一行:州
第二行:城镇
第 3-5 行和第 6-8 行:数据
REPEAT

soo...由于某种原因,ifstream 只给了我 16 个元素(16 个城镇)。嗯……

【问题讨论】:

  • Kirchheim am Neckar -- std::string::operator >> 最多只能读取第一个空格字符。也许这就是你没有得到所有数据的原因,或者至少这似乎是你读入输入的一个缺陷。你只会得到Kirchheim 而不是Kirchheim am Neckar

标签: c++ file iostream ifstream


【解决方案1】:

使用移位运算符读取std::string 只读取一个单词。默认情况下,单词由空格分隔。结果,字符串Kirchheim am Neckar 将不会被完全读取,而只会读取Kirchheim。当尝试将am 读取为整数时,流将进入故障模式并拒绝读取任何内容,直到其标志为clear()ed。

您可能想通过阅读整行来了解城镇和州。使用std::getline(stream, str) 这样做。此外,总是在读取尝试之后测试您的读取操作是否成功。使用流的惯用方式是

while (x >> t) {
    ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-10
    • 2020-12-06
    • 1970-01-01
    • 2014-08-28
    • 1970-01-01
    • 2023-01-30
    • 1970-01-01
    相关资源
    最近更新 更多