在C++中处理网格数据的输入输出,通常需要使用二维数组或者std::vector
#include<iostream>
#include <fstream>
#include<vector>
int main() {
std::ifstream input_file("grid_data.txt");
int rows, cols;
input_file >> rows >> cols;
std::vector<std::vector<int>> grid(rows, std::vector<int>(cols));
for (int i = 0; i< rows; ++i) {
for (int j = 0; j< cols; ++j) {
input_file >> grid[i][j];
}
}
input_file.close();
// 处理网格数据...
return 0;
}
#include<iostream>
#include <fstream>
#include<vector>
int main() {
int rows = 3, cols = 4;
std::vector<std::vector<int>> grid = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
std::ofstream output_file("grid_data_output.txt");
output_file<< rows << " "<< cols << "\n";
for (int i = 0; i< rows; ++i) {
for (int j = 0; j< cols; ++j) {
output_file<< grid[i][j] << " ";
}
output_file << "\n";
}
output_file.close();
return 0;
}
这两个示例分别展示了如何从文件中读取网格数据以及将网格数据写入文件。你可以根据实际需求对这些代码进行修改和扩展。