【问题标题】:Reading file, storing in array, error: no match for 'operator>>'读取文件,存储在数组中,错误:'operator>>' 不匹配
【发布时间】:2015-09-19 22:44:06
【问题描述】:

我有一个文件 weights01.txt,其中填充了 4x3 矩阵中的浮点数,如下所示

1.1 2.123 3.4
4.5 5 6.5
7 8.1 9
1 2 3.1

我正在尝试读取此文件并将数据传输到名为 newarray 的数组中。这是我正在使用的代码:

int main()
{
  ofstream myfile;
  float newarray[4][3];
  myfile.open ("weights01.txt");
    for(int i = 0 ; i < 4; i++)   // row loop
    {
        for(int j = 0 ; j < 3; j++)  // column loop
        {
            myfile >> newarray[i][j]; // store data in matrix
        }
    }
  myfile.close();
  return 0;
}

我的行有错误

myfile >> newarray[i][j];

错误:'myfile >> newarray[i][j]'中的'operator>>'不匹配

我不明白为什么会出现这个错误

我搜索了有关此“不匹配'运算符>>'错误的先前问题,包括thisthis。我还阅读了this 关于重载运算符的长时间讨论,但我没有找到解释(可能是因为我以前很少使用文件,也没有真正关注正在发生的事情。

【问题讨论】:

    标签: c++ file ofstream


    【解决方案1】:

    您无法读取std::ofstreamout 文件流的缩写),它仅用于输出。 请改用std::ifstream(即in 文件流)。

    如果您对哪个标准库工具做什么有疑问,请查看您最喜欢的参考资料,例如cppr


    OT备注:可以直接从文件名构造流:

    std::ifstream myfile ("weights01.txt");
    

    完成后您不需要close() 文件,流的析构函数会为您处理。

    【讨论】:

      猜你喜欢
      • 2011-10-06
      • 2011-12-10
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-02
      • 1970-01-01
      相关资源
      最近更新 更多