Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/156.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ ifstream读取以_C++_File_Ifstream - Fatal编程技术网

C++ ifstream读取以

C++ ifstream读取以,c++,file,ifstream,C++,File,Ifstream,我有多个文件以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

我有多个文件以
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_u880;”+*
上有一个错误。当我想到它时,它不起作用是有道理的。我想我需要一个循环什么的,我只是不知道怎么做。

使用特定于操作系统的API枚举可用文件,并将名称存储在容器中,例如字符串向量
std::vector v。在容器上迭代:

for (auto el : v) {
    std::ifstream file(el);
    // the code
}
如果您确实知道存在具有基于范围的硬编码值的现有文件,则可以在
for
循环中使用该函数:

for (size_t i = 0; i < 4000; i++) {
    std::ifstream file("employee_" + std::to_string(i) + ".txt");
    // the code
}
(大小i=0;i<4000;i++)的
{
std::ifstream文件(“employee_”+std::to_string(i)+”.txt”);
//代码
}
更新:

正如评论中指出的,OS API的替代方案是C++17标准和。

使用特定于OS的API枚举可用文件,并将名称存储在容器中,如字符串向量
std::vector v。在容器上迭代:

for (auto el : v) {
    std::ifstream file(el);
    // the code
}
如果您确实知道存在具有基于范围的硬编码值的现有文件,则可以在
for
循环中使用该函数:

for (size_t i = 0; i < 4000; i++) {
    std::ifstream file("employee_" + std::to_string(i) + ".txt");
    // the code
}
(大小i=0;i<4000;i++)的
{
std::ifstream文件(“employee_”+std::to_string(i)+”.txt”);
//代码
}
更新:

正如评论中指出的那样,OS API的替代方案是C++17标准和。

中的支持。您需要遍历目录并首先获取所有文件名。然后,您需要查看其中哪些以“employee”开头并打开它们。遍历目录的代码将取决于您所处的平台。我在Mac上,但我希望使用最通用的方法。如果编译器不支持std::filesystem,则Post::filesystem可能会有所帮助。您需要遍历目录并首先获取所有文件名。然后,您需要查看其中哪些以“employee”开头并打开它们。在目录中迭代的代码将取决于你在哪个平台上。我在Mac上,但是我想要最通用的BoovioBoosi::如果编译器不支持STD::文件系统可能会帮助:文件系统。C++ 17引入了一个,这样OP就可以避免OS特定的API。我认为第一个解决方案是最好的,如果你有一些“漏洞”的话。在员工编号中,因为这样可以避免多次尝试打开不存在的文件。如果数字是连续的,第二种方法是最好的。最简单的方法是使用
for(size\u t i=0;i<4000;i++)
loopC++17引入了一个,因此OP可能能够避免特定于操作系统的API。我认为第一种解决方案是最好的,如果员工数字中存在一些“漏洞”,因为这样可以避免多次尝试打开不存在的文件。如果数字是连续的,则第二种方法是最好的。最简单的方法是使用
for(size\u t i=0;i<4000;i++)
循环