gpt4 book ai didi

c++ - 如何从 .t​​xt 文件读取表格到 C++

转载 作者:太空狗 更新时间:2023-10-29 20:16:28 24 4
gpt4 key购买 nike

我想从文件中读取矩阵并在我的程序中使用它。但是当我输出结果时,它显示它没有正确读取。这是代码:

#define I 5 
#define J 5
#define P 2

int i,j,k; //for loops

int main ()
{
ifstream inFile;
ofstream outFile;
double C[I][J];

inFile.open("C.txt", ios::in);
if (! inFile) {
cerr << "unable to open file C.txt for reading" << endl;
return 1;
}

for(i=0; i<I; i++)
for(j=0; j<J; j++)
inFile >> C[i][j];

outFile.open("results.txt");
outFile<< "C" <<endl;
for(i=0;i<I;i++)
{
for(j=0;j<J;j++)
outFile<< C[i][j];
outFile<< endl;
}

inFile.close();
outFile.close();

return 0;
}

C 是一个整数值矩阵 2 3 5... 但我得到的是

316-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061 -9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061-9.25596e+061

最佳答案

你应该在每个数字后输出一个空格,否则它们会粘在一起。

outFile<< C[i][j] << " ";

您还应该检查输入的有效性。此处不显示(您已经知道如何检查 if (!inFile))。

关于c++ - 如何从 .t​​xt 文件读取表格到 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9447787/

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