How to put the content of a file into an array in C++?
You can read the content of the file into an array using the following steps:
- Open the file:
#include <fstream>
std::ifstream file("filename.txt");
- Check if the file was successfully opened.
if (!file.is_open()) {
// 文件打开失败
return;
}
- Create an array to store the content of the files.
const int MAX_SIZE = 100; // 数组的最大大小
int arr[MAX_SIZE];
int count = 0; // 记录数组中元素的个数
- Read the file content in a loop and store it in an array.
int num;
while (file >> num) {
arr[count] = num;
count++;
if (count >= MAX_SIZE) {
// 数组已满,无法继续读取
break;
}
}
- Close the file.
file.close();
Complete code example:
#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;
}
Please make sure to replace “filename.txt” with the actual file name and create the file in the same directory.