c++读取文件内容怎么放入数组
您可以使用以下步骤将文件内容读取到数组中:
- 打开文件:
#include <fstream>
std::ifstream file("filename.txt");
- 检查文件是否成功打开:
if (!file.is_open()) {
// 文件打开失败
return;
}
- 定义一个数组来存储文件内容:
const int MAX_SIZE = 100; // 数组的最大大小
int arr[MAX_SIZE];
int count = 0; // 记录数组中元素的个数
- 使用循环读取文件内容,并将其存入数组中:
int num;
while (file >> num) {
arr[count] = num;
count++;
if (count >= MAX_SIZE) {
// 数组已满,无法继续读取
break;
}
}
- 关闭文件:
file.close();
完整的代码示例:
#include <iostream>
#include <fstream>
const int MAX_SIZE = 100; // 数组的最大大小
int main() {
std::ifstream file("filename.txt");
if (!file.is_open()) {
std::cout << "文件打开失败" << std::endl;
return 0;
}
int arr[MAX_SIZE];
int count = 0;
int num;
while (file >> num) {
arr[count] = num;
count++;
if (count >= MAX_SIZE) {
std::cout << "数组已满,无法继续读取" << std::endl;
break;
}
}
file.close();
// 打印数组中的内容
for (int i = 0; i < count; i++) {
std::cout << arr[i] << " ";
}
std::cout << std::endl;
return 0;
}
请确保将"filename.txt"替换为实际文件名,并在同一目录下创建该文件。