在C++中,可以使用文件流和二维数组来将整数文件读入二维整数数组。下面是一个示例代码:
#include <iostream>
#include <fstream>
#include <vector>
int main() {
std::ifstream inputFile("input.txt"); // 替换为你的文件路径
if (!inputFile) {
std::cout << "无法打开文件" << std::endl;
return 1;
}
std::vector<std::vector<int>> array; // 二维整数数组
int rows, cols;
inputFile >> rows >> cols; // 读取行数和列数
// 根据行数和列数初始化二维数组
array.resize(rows, std::vector<int>(cols));
// 逐行读取整数并存入二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
inputFile >> array[i][j];
}
}
// 打印二维数组
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
inputFile.close();
return 0;
}
上述代码中,首先使用ifstream
打开文件,并检查文件是否成功打开。然后,通过读取文件中的行数和列数,初始化二维数组。接下来,使用嵌套的循环逐行读取整数,并将其存入二维数组中。最后,打印二维数组的内容。
请注意,上述代码中的文件路径应替换为你实际使用的文件路径。此外,代码中没有提及任何特定的云计算品牌商或产品,因为这与文件读取操作无关。
领取专属 10元无门槛券
手把手带您无忧上云