在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;
}
這兩個示例分別展示了如何從文件中讀取網格數據以及將網格數據寫入文件。你可以根據實際需求對這些代碼進行修改和擴展。