首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

只从输入目录读取.txt文件,然后将所有内容放入C++中的一个数组中

问:只从输入目录读取.txt文件,然后将所有内容放入C++中的一个数组中。

答:在C++中,可以使用以下步骤实现只从输入目录读取.txt文件,并将所有内容放入一个数组中:

  1. 引入必要的头文件:
代码语言:txt
复制
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
  1. 定义一个函数来读取目录中的.txt文件并将内容存入数组:
代码语言:txt
复制
std::vector<std::string> readTxtFilesFromDirectory(const std::string& directoryPath) {
    std::vector<std::string> contentArray;

    for (const auto& entry : std::filesystem::directory_iterator(directoryPath)) {
        if (entry.path().extension() == ".txt") {
            std::ifstream file(entry.path());
            std::string line;

            while (std::getline(file, line)) {
                contentArray.push_back(line);
            }

            file.close();
        }
    }

    return contentArray;
}
  1. 在主函数中调用该函数并输出结果:
代码语言:txt
复制
int main() {
    std::string directoryPath = "输入目录的路径";
    std::vector<std::string> contentArray = readTxtFilesFromDirectory(directoryPath);

    for (const auto& content : contentArray) {
        std::cout << content << std::endl;
    }

    return 0;
}

以上代码会遍历指定目录中的所有文件,筛选出扩展名为.txt的文件,并将每个文件的内容逐行存入一个字符串数组中。最后,通过循环输出数组中的内容。

这个方法适用于C++开发者需要从指定目录中读取.txt文件并将内容存入数组的场景。如果需要更多关于C++开发、文件操作、目录遍历等方面的帮助,可以参考腾讯云的C++开发者文档:C++开发者文档

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券