6

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

#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

编译程序后,它会打印这个

在此处输入图像描述

4

3 回答 3

4

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

最后但同样重要的是,您应该在读取后立即测试 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;
}
于 2015-12-14T19:17:27.403 回答
1

您可能想研究使用向量,以便您可以拥有一个动态数组。

于 2015-12-14T18:50:56.197 回答
0

尝试:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
using namespace std;
int main() {
  fstream f;
  int i, j, n, a[20][20];
  string buf;

  i = 0;
  j = 0;
  n = 0;
  f.open("array.txt", ios::in);
  while (1) {
    getline(f, buf);
    if (f.eof()) break;
    stringstream buf_stream(buf);
    j = 0;
    do {
      buf_stream >> a[i][j];
      j++;
    } while (!buf_stream.eof());
    i++;
    n++;
  }

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

此外,如果您真的想读取任意大的数组,那么您应该使用std::vector或其他一些容器,而不是原始数组。

于 2015-12-14T19:16:18.320 回答