gpt4 book ai didi

c++ - 如何在不知道 C++ 长度的情况下从文件中读取二维数组?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:33:57 25 4
gpt4 key购买 nike

正如标题所说,我正在尝试从文件中读取未知数量的整数并将它们放入二维数组中。

#include <iostream>
#include <fstream>
using namespace std;
int main()
{

fstream f;int i,j,n,a[20][20];char ch;

i=0;j=0;n=0;
f.open("array.txt", ios::in);
while(!f.eof())
{
i++;
n++;
do
{
f>>a[i][j];
j++;
f>>ch;
}
while(ch!='\n');
}

for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
cout<<a[i][j]<<endl;
cout<<endl;
}
return 0;

和我的“array.txt”文件:

1 1 1
2 2 2
3 3 3

程序编译后打印出这个

enter image description here

最佳答案

由于您的输入文件是面向行的,因此您应该使用 getline(C++ 等价物或 C fgets)读取一行,然后使用 istringstream 将该行解析为整数.由于您先验不知道大小,因此您应该使用 vector ,并始终控制所有行具有相同的大小,并且行数与列数相同。 p>

最后但同样重要的是,您应该在读取后立即测试eof,而不是在循环开始时测试。

代码变为:

#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main()
{

fstream f;
int i=0, j=0, n=0;
string line;
vector<vector<int>> a;
f.open("array.txt", ios::in);
for(;;)
{
std::getline(f, line);
if (! f) break; // test eof after read
a.push_back(vector<int>());
std::istringstream fline(line);
j = 0;
for(;;) {
int val;
fline >> val;
if (!fline) break;
a[i].push_back(val);
j++;
}
i++;
if (n == 0) n = j;
else if (n != j) {
cerr << "Error line " << i << " - " << j << " values instead of " << n << endl;
}
}
if (i != n) {
cerr << "Error " << i << " lines instead of " << n << endl;
}

for(vector<vector<int>>::const_iterator it = a.begin(); it != a.end(); it++) {
for (vector<int>::const_iterator jt = it->begin(); jt != it->end(); jt++) {
cout << " " << *jt;
}
cout << endl;
}
return 0;
}

关于c++ - 如何在不知道 C++ 长度的情况下从文件中读取二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34274291/

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