简体   繁体   中英

C++ reading multiple .txt files into string array

So I have a folder with different .txt files and I want to read the file names from generated test.txt file into string array:

string find_files()
{
string fileNames[20];
system("dir /b > test.txt");

ifstream inFile("test.txt");
if (!inFile)
{
    cout << "File cannot be opened." "\n";
    return;
}

for (string line; getline(inFile, line); )
{
    istringstream in(line);
    for (int i = 0; i < 20; i++)
        in >> fileNames[i];
}
return fileNames[20];
}

that is the function to find the file names but actually it has some problem. Please help me.

Problem 1: dir /b should put one file per line in your file. Your nested loops causes you to read each line, but for each line, you read line content in the nested loop, restarting everytimes with i=0 . So you overwrite every time the same and unique fileNames[0] .

Problem 2: if one of your filename would contain a space, your code in>> fileNames[i]; would process it as if it were several filenames (the space acts as separator).

Problem 3: You can't return an array by value. return fileNames[20]; doesn't return an array with 20 elements int it, but returns the 21st element of the array. Unfortunately, you go out of bounds which is undefined behavior.


Solution to 1 and 2:

If you assume 1 filename per line, you could simply do:

for (int i; i<20 && getline(inFile, fileNames[i]); i++)
    ;

If you want to read several filenames per line:

string line; 
int i=0; 
while (getline(inFile, line) )
{
    istringstream in(line);
    for ( ; i < 20; i++)   // don't reset the counter
        in >> fileNames[i];
}

Solution to 3:

There is an easy way to solve it, if you're allowed to use vectors. Then just replace the array with a vector, and push_back() the strings into it (no logner need to keep track of the i counter).

If you're not allowed to do so, I'd suggest to pass the address of the array :

int find_files(string fileNames[], int maxfiles)
{
    ...  // replace 20 by maxfiles 
    return i;  // return the number of elements read. 
}

Did you check if your file has 21 lines of text at all? If not 21th string of fileNames array will be empty. 21th string is the one with index 20: fileNames[20] .

And: for (int i = 0; i < 20; i++) You are iterating i from 0 to 19, it will never reach index 20 and you are returning value fileNames[20] from your function.

There is also a huge error in code. You defined string fileNames[20]; which creates an array of 20 strings, indexed from 0 to 19 . So it is only valid to use values from fileNames[0] to fileNames[19] . Using fileNames[20] can cause unpredictable results, crash your program, it is simply wrong .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM