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