簡體   English   中英

如何在不知道C ++長度的情況下從文件中讀取二維數組?

[英]How to read a 2d array from a file without knowing its length in C++?

就像標題所說我試圖從文件中讀取未知數量的整數並將它們放在二維數組中。

#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

編譯程序后,打印出來

在此輸入圖像描述

由於您的輸入文件是面向行的,因此您應該使用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;
}

您可能希望查看使用向量,以便擁有動態數組。

嘗試:

#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或其他一些容器,而不是原始數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM