温馨提示×

c++读取文件内容怎么放入数组

c++
小亿
167
2024-01-13 19:08:13
栏目: 编程语言

您可以使用以下步骤将文件内容读取到数组中:

  1. 打开文件:
#include <fstream>

std::ifstream file("filename.txt");
  1. 检查文件是否成功打开:
if (!file.is_open()) {
    // 文件打开失败
    return;
}
  1. 定义一个数组来存储文件内容:
const int MAX_SIZE = 100; // 数组的最大大小
int arr[MAX_SIZE];
int count = 0; // 记录数组中元素的个数
  1. 使用循环读取文件内容,并将其存入数组中:
int num;
while (file >> num) {
    arr[count] = num;
    count++;
    if (count >= MAX_SIZE) {
        // 数组已满,无法继续读取
        break;
    }
}
  1. 关闭文件:
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"替换为实际文件名,并在同一目录下创建该文件。

0