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

   2025-02-05 4040
核心提示:您可以使用以下步骤将文件内容读取到数组中:打开文件:#include fstreamstd::ifstream file(filename.txt);检查文件是否成功打

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

打开文件:
#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"替换为实际文件名,并在同一目录下创建该文件。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言