Open files in a "sorted" order to work on them

Jun 22, 2014 at 11:23am
Hello,
My problem is, I have data files named data001 -> data999, I need to somehow input a number n from the console and open files from data001 to datan using an std::ifstream fin to work on them one by one. What I'm thinking of right now is having a string s = "data" and running a loop from 1 to n. For example when the loop is at 1 I'll have s += "001"; and fin.open(s); but that takes too many if conditions and making the code looks a bit ugly. Is there a better approach for me?

Thank you for your help and sorry if I'm not clear enough (I'm not an English speaker), if you want to ask something that would help you help me, please do.
Jun 22, 2014 at 12:15pm
Take a look:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <iomanip>
#include <sstream>

int main()
{
    for(int i = 1; i < 1000; ++i) {
        std::ostringstream name;
        name << "data" << std::setfill('0') << std::setw(3) << i;
        std::cout << name.str() << '\n';
    }
}
data001
data002
data003
data004
data005
data006
data007
data008
data009
data010
data011
<SKIPPED>
data996
data997
data998
data999
Jun 23, 2014 at 1:29am
Thank you very much! That works wonderfully, I haven't used stringstream before but I guess it's time to learn something new.
Topic archived. No new replies allowed.