c++ - 从C++中的txt文件中读取字符

标签 c++ arrays file-io

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

我希望你明白了。

最佳答案

你可以这样做:

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

关于c++ - 从C++中的txt文件中读取字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12320969/

相关文章:

javascript - 查找循环数组中任意两个索引之间的中间索引

python - 在 Python 中读取大文件的惰性方法?

Java读取文本文件2列并存储在数组中

c++ - 您如何将 CreateThread 用于作为类成员的函数?

c++ - OpenCL:cl::getDevices 崩溃

c++ - 如何用 Cython 包装 C++ 类?

javascript - Javascript 中的动态 setInterval

c - 数组到指针与二维数组

c - C 中的文件 IO 和字符串意外值

c++ - MS Visual Studio 如何更新语言 SDK?