我有多个以 employee_
开头的文件
Examples :
employee_2053.txt
employee_1284.txt
employee_4302.txt
etc...
我想要的是读取每个文件的内容。我试过这样的事情:
string fname, lname;
ifstream file("employee_" + *);
while(file>>fname>>lname) {
// Do something here that is gonna be repeated for every file
}
我在 "employee_"+ *
处出错。当我考虑它时,它不起作用是有道理的。我想我需要一个循环或其他东西,我只是不知道该怎么做。
最佳答案
使用特定于操作系统的 API 枚举可用文件并将名称存储在容器中,例如字符串 vector std::vector<std::string> v;
.遍历容器:
for (auto el : v) {
std::ifstream file(el);
// the code
}
如果您确定存在具有基于范围的硬编码值的现有文件,您可以使用 std::to_string for
中的函数循环:
for (size_t i = 0; i < 4000; i++) {
std::ifstream file("employee_" + std::to_string(i) + ".txt");
// the code
}
更新:
正如评论中指出的那样,OS API 的替代方案是 file system。支持 C++17 标准和 Boost Filesystem Library .
关于c++ - ifstream 读取所有以开头的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48466627/