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:

  1. Open the file:
#include <fstream>

std::ifstream file("filename.txt");
  1. Check if the file was successfully opened.
if (!file.is_open()) {
    // 文件打开失败
    return;
}
  1. Create an array to store the content of the files.
const int MAX_SIZE = 100; // 数组的最大大小
int arr[MAX_SIZE];
int count = 0; // 记录数组中元素的个数
  1. 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;
    }
}
  1. 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.

bannerAds