我正在尝试将一个正好有 70x50 个数字的文件中的 float 读入一个二维数组。当我读入文件并计算数组中的数据时,我得到了正确的数字。但是当我读入文件后尝试使用数组中的数据时,数据是乱码。读取文件后需要分配堆内存持久化吗?代码如下:
int main() {
fstream file("numbers.txt");
if (!file) {
cerr << "Sample data could not be opened" << endl;
system("PAUSE");
exit(1);
}
float data[70][50];
for (int i = 0; i < 70; i++){
for (int j = 0; j < 50; j++) {
float n;
file>> n;
data[i][j] = n;
cout << data[i][j];
}
}
cout << data[70][50];
system("PAUSE");
face.close();
return(0);
}
最佳答案
这一行会产生未定义的行为
cout << data[70][50];
该数组的维度为 [70][50]
,这意味着最后的有效索引为 [69][49]
。
直接回答您的问题:
Do I need to allocate heap memory to persist after the file is read?
没有。您的数组 data
非常好。如果你要遍历它并 cout
从 [0][0]
到 [69][49]
的所有值你会注意到这些值将是正确的。
关于c++ - 从文本文件中读取 float 一直有效,直到超出 ifstream 范围 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789150/