ldj979
ldj979

Reputation: 3

How do I read Files with similar names in c++

total1_0831.txt

total2_0831.txt

total3_0831.txt

total1_0901.txt

total2_0901.txt

I want to load 3 0831 text files

my code is

fstream myTxT;
myTxT.open("total1_0831.txt");

fstream myTxT;
myTxT.open("total2_0831.txt");

fstream myTxT;
myTxT.open("total3_0831.txt");

It was ineffective, so I wrote the code in a new way.

vector<fstream> myTxT;
myTxT.open("total%d_0831.txt") // i think this part is error, but i don't know how to fix it

This code wasn't work anymore.

Any advice would be appreciated

Upvotes: 0

Views: 54

Answers (1)

89f3a1c
89f3a1c

Reputation: 1488

You should have a base string, to which you then append the number of the file to read as a string, and finally append the extension.

Once you have the path string constructed, you can load the file.

All this logic should go in a loop, and you're done!

Having said that, it probably is an overkill for just 3 files, but it's a nice method when dealing with multiple files that share a logic in their naming.

Upvotes: 1

Related Questions