0

我有一个程序可以从 txt 文件中读取行数和列数。此外,程序必须从同一文件中读取二维数组的内容。

这是txt文件

8 20
 *       
  *
*** 


         ***

8 和 20 分别是行数和列数。空格和星号是数组的内容, Array[8][20]例如,Array[0][1] = '*'

我确实使程序读取 8 和 20 如下:

ifstream myFile;
myFile.open("life.txt");

if(!myFile) {
    cout << endl << "Failed to open file";
    return 1;
}

myFile >> rows >> cols;
myFile.close();

grid = new char*[rows];
for (int i = 0; i < rows; i++) {
    grid[i] = new char[cols];
}

现在,如何将空格和星号分配给数组中的字段?

我做了以下,但没有奏效

for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            while ( myFile >> ch )
            {
            grid[i][j] = ch;
            }
        }
    }

我希望你明白了。

4

2 回答 2

3

你可以这样做:

for (int y = 0; y < rows; y++) {
    for (int x = 0; x <= cols; x++) {
        char ch = myFile.get();
        if (myFile.fail()) <handle error>;
        if (ch != '\n') grid[y][x] = ch;
    }
}
于 2012-09-07T15:36:51.917 回答
0
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    ifstream myFile("file.txt");

    if(!myFile) { 
      cout << endl << "Failed to open file";
        return 1;
    }

    int rows = 0, cols = 0;
    myFile >> rows >> cols;

    vector<vector<char> > grid(rows, vector<char>(cols));
    for(int i = 0;i < rows;i++)
    {
        for(int j = 0;j < cols;j++)
        {
            if(myFile.fail()) {cout << "Improper data in file" << endl;}
            myFile >> grid[i][j];
        }
    }
    myFile.close();

    //Printing the grid back
    std::cout << "This is the grid from file: " << endl;
    for(int i = 0;i < rows;i++)
    {
        cout << "\t";
        for(int j = 0;j < cols;j++)
        {
            cout << grid[i][j];
        }
        cout << endl;
    }
}
于 2012-09-07T18:13:46.133 回答