我有一个程序可以读取txt文件中的行数和列数。此外,程序必须从同一文件中读取2D数组的内容。
这是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;
}
}
}
我希望你明白这一点。
答案 0 :(得分: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;
}
}
答案 1 :(得分: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;
}
}