简体   繁体   English

从C ++中的txt文件读取char

[英]Read char from txt file in C++

I have a program that will read the number of rows and columns from a txt file. 我有一个程序可以从txt文件读取行数和列数。 Also, the program has to read the contents of a 2D array from the same file. 另外,程序必须从同一文件中读取2D数组的内容。

Here is the txt file 这是txt文件

8 20
 *       
  *
*** 


         ***

8 and 20 are the number of rows and columns respectively. 8和20分别是行数和列数。 The spaces and asterisks are the contents of the array, Array[8][20] For example, Array[0][1] = '*' 空格和星号是数组Array[8][20]的内容,例如Array[0][1] = '*'

I did make the program reading 8 and 20 as follow: 我确实使程序读取如下的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];
}

Now, how to assign the spaces and the asterisks to to the fields in the array? 现在,如何将空格和星号分配给数组中的字段?

I did the following, but it didn't work 我做了以下工作,但是没有用

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

I hope you got the point. 我希望你明白了。

You can do something like this: 您可以执行以下操作:

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;
    }
}
#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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM