【问题标题】:Read char from txt file in C++从 C++ 中的 txt 文件中读取字符
【发布时间】:2012-09-07 15:19:44
【问题描述】:

我有一个程序可以从 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;
            }
        }
    }

希望你明白了。

【问题讨论】:

  • 为什么在读取行和列后关闭文件?
  • 如果您将文件中的空格替换为点,会更容易。
  • 在关闭文件之前读取空格和星号
  • 你为什么不接受你的问题?
  • 请不要转发您完全相同的问题。

标签: c++ arrays file-io


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 这样的事情是对的。因为这肯定会破坏换行符。
【解决方案2】:
#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;
    }
}

【讨论】:

  • 你的代码有问题,但我不知道它在哪里......它没有工作......不过谢谢!
  • 这是不可能的。我只是在测试时才把它放在这里。你能告诉我是什么问题吗?
  • 在读取文件之前是否必须初始化grid[i][j]
  • stackoverflow.com/questions/5222404/… 请参阅此处以获取答案。如果你得到它的工作,请接受/赞成答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-09
  • 2015-01-28
  • 2021-07-07
相关资源
最近更新 更多