【问题标题】:Why isn't array filling?为什么不填充数组?
【发布时间】:2012-10-28 05:08:40
【问题描述】:

我正在尝试用 fstream 填充两个数组。一个是字符串,一个是整数。字符串数组(名称)填充良好,但字符数组只填充第一个值。

void fillInventory(ifstream &fin, int costArray[],string itemArray[])
{
    string name = "junk";
    string cost;
    int i = 0;
    int max = 0;
    stringstream convert;

    while(name != "none")
    {
        getline(fin, name);
        getline(fin, cost);
        if(name != "none")
        {
            itemArray[i] = name;
            convert<<cost;
            convert >> costArray[i];
        }
        i++;
    }
}

我是在使用 stringstream 错误还是我的逻辑不正确,或者完全是其他什么?

【问题讨论】:

  • 成本是整数,对吗?
  • 是的,我认为这对我来说是最简单的方法。
  • 你的整个 int 数组是填充了第一个值,还是只填充了数组的第一个元素?
  • 尝试将 convert 的 decl 移动到与其使用相同的块?
  • @Chris,这只是第一个值被填充,其余的保持在 0(初始化值)

标签: c++ arrays


【解决方案1】:

当你这样做时:

convert >> costArray[i];

您已到达字符串流上的 EOF,它设置了 eofbit 标志,导致未来的操作失败。重置标志以继续:

convert >> costArray[i];
convert.clear();

【讨论】:

  • 太棒了,谢谢大家。希望我能给你们两个接受。它设置了什么标志,你能解释一下或给我一个好的参考吗?(我刚开始学习 9 月...)
  • @DanielBall,en.cppreference.com/w/cpp/io/basic_iostream。当operator&gt;&gt; 命中 EOF 时,它会设置eofbit,这意味着它到达了文件末尾。这使得未来的操作保持不变。如果您 cin 一个 int 但输入一个字符,您也会看到此行为。使用 clear() 会重置标志。 fail() 在 EOF 上返回 true 的好处是它允许一个很好的循环:while (cin &gt;&gt; num) 或 while (fin &gt;&gt; num)。
  • 谢谢克里斯,我会尽量记住这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多