读取文件,存储在数组中,错误:'operator>>'不匹配

Reading file, storing in array, error: no match for 'operator>>'

本文关键字:gt 不匹配 operator 错误 存储 文件 数组 读取      更新时间:2023-10-16

我有一个文件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];

错误:没有匹配'operator>>'在'myfile>> newarray[i][j]'

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

我搜索了以前关于这个"no match for 'operator>>"错误的问题,包括这个和这个。我还阅读了这篇关于重载操作符的长篇讨论,但我没有找到解释(可能是因为我以前没有经常使用文件,并且没有真正了解发生了什么)。

您不能从std::ofstream (out文件流的缩写)中读取,它仅用于输出。使用std::ifstream(即文件流中的)代替。

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


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

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

和你不需要close()文件当你完成后,流的析构函数将为你处理