Hi all,

I'm sure it's an error by me, but I'm having a problem with ifstream inside a loop. The reason for the loop is read in a piece of text from multiple files, and cases within the switch statement change the filename, path is previously declared.

The first iteration of the for loop always works and the value "chamberarrayval" is output, but the subsequent values from the subsequent files never materialise. The switch statement is OK as I've tried the cases in isolation without the loop. Do I need to define ifstream everytime or something else? Any help much appreciated.

double openfunc(void){

       // loop through files
       for(int j=1;j<5;j++){

        // switch statement to changed filename
        switch(j){

        case 1: fileName = path.append("file1");
            break;
        case 2: fileName = path.append("file2");
            break;
        case 3: fileName = path.append("file3");
            break;
        case 4: fileName = path.append("file4");
            break;
                 }

    // open selected file
    ifstream infile(fileName.toStdString().c_str());

    //define vector and string
    vector<string> lines;
    string line;

    // read file into vector line by line
    while (getline(infile, line)){

         lines.push_back(line);

    }
    infile.close();

    // loop through vector line by line
    for (int i = 0; i < lines.size(); i++){

       str = lines[i];

        // information required is on line 744
        if (i==744){

            centralchamber = str.substr(9,10);

            chamberarrayval = atof(centralchamber.c_str());

            cout << chamberarrayval << endl;

        }

     }

 }
   }

whenever ye' are using a fstream object multiple times, you should clear the object before using it again.

try calling infile.clear() in the beginning of your function and see if that helps.

Are you sure that calling path.append("file1") does not change the string stored in "path"? I would bet that is the problem, in fact, I know.

Try using this instead:

// switch statement to changed filename
        switch(j){

        case 1: fileName = path + "file1";
            break;
        case 2: fileName = path + "file2";
            break;
        case 3: fileName = path + "file3";
            break;
        case 4: fileName = path + "file4";
            break;
                 }

Thanks for the reply CP, your suggestion hasn't worked unfortunately :( Any other suggestions?

Are you sure that calling path.append("file1") does not change the string stored in "path"? I would bet that is the problem, in fact, I know.

Perfect, it was this. Many thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.