gpt4 book ai didi

c++ - 读取文件,存入数​​组,报错: no match for 'operator>>'

转载 作者:太空宇宙 更新时间:2023-11-04 16:07:46 24 4
gpt4 key购买 nike

我有一个文件 weights01.txt,它在 4x3 矩阵中填充了 float ,如下所示

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>>”不匹配

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

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

最佳答案

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

如果您对哪个标准库工具的作用有疑问,请查看您最喜欢的引用资料,例如 cppr .


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

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

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

关于c++ - 读取文件,存入数​​组,报错: no match for 'operator>>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32673933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com