crazycrazy
crazycrazy

Reputation: 15

Can I loop over file names that differ only by an integer number?

I have 100 files called "realization_i.dat", where i is an integer from 0 to 99.

I want to loop over each file in order to import the data for use in manipulation in my code.

I'm unsure on how to do this, but this is what I have so far:

for (int i = 0; i < 99; i++) {

    string path = "/Users/Olly/Documents/BScProject/WeakLensing/SIGNAL/";
    string mainFile = path + "realization_" << i << ".dat";
    vector <double> Pos1, Pos2, E1, E2, Z, W, SC;
    ifstream in(mainFile.c_str(), ios::in);

My thoughts are that, for i = 0, I would be inputting the data from the realization_0.dat file, and then realization_1.dat file, etc. up to realization_99.dat.

I am getting the following error:

ShearStacks.cpp:41:49: error: invalid operands to binary expression
      ('std::__1::basic_string<char>' and 'int')
        string mainFile = path + "realization_" << i << ".dat";

Can anyone explain why this doesn't work and suggest a new way of looping over the files? (Quite new to C++.)

Upvotes: 1

Views: 55

Answers (3)

2785528
2785528

Reputation: 5566

The string 'mainFile' can not used that way.

I would suggest using a std::stringstream :

std::stringstream ss;
ss << "/Users/Olly/Documents/BScProject/WeakLensing/SIGNAL/"
   << "realization_" << i << ".dat";

std::string mainFile = ss.str();

Upvotes: 0

MFH
MFH

Reputation: 1734

A string is not a stream!

Use normal string-concatenation:

 string mainFile = path + "realization_" + std::to_string(i) + ".dat";

Note that to_string is only available starting with C++11.

Upvotes: 0

WhiZTiM
WhiZTiM

Reputation: 21576

As per operator precedence, the + operation will happen first. (path + "realization_") << i << ".dat"; then the compiler will attempt to look for a suitable operator << between the resulting std::string and an int which isn't available, then it chokes.

You probably want to use std::to_string to convert your numbers to string:

for (int i = 0; i < 2; i++) {

    string path = "/Users/Olly/Documents/BScProject/WeakLensing/SIGNAL/";

    string mainFile = path + "realization_" + std::to_string(i) + ".dat";

    vector <double> Pos1, Pos2, E1, E2, Z, W, SC;
    ifstream in(mainFile.c_str(), ios::in);
    ......
}

Upvotes: 1

Related Questions