pbhuter
pbhuter

Reputation: 437

C++ read two input files differently

I have two files listed in "input.txt", I can read in the first one using:

while (getline(inFile, name))
{
    datFile.open(name, ifstream::in);
    ...
}

But when it gets to the end of processing datFile, it will go back and try to open the other file (second file listed in "input.txt", which I do not want to process the same way. How can I open the second file and process it differently than the first?

Thanks.

Upvotes: 1

Views: 1711

Answers (3)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 132984

You must have three ifstream objects;

std::ifstream inFile("input.txt");
std::ifstream file1;
std::ifstream file2;

std::string fileName1, fileName2;
getline(inFile, fileName1);
getline(inFile, fileName2);

file1.open(fileName1, open as you ilke);
file2.open(fileName2, open as you like);

process both files independently.

Alternatively, if keeping the file open is undesirable, rewrite the last three lines as:

file1.open(fileName1, open as you ilke);
process file1;
file1.close();   

file2.open(fileName2, open as you like);
process file2;
file2.close();   

In the second scenario you can use the same ifstream object.

Upvotes: 1

David
David

Reputation: 322

If you are guaranteed to have two files in your input.txt file (inFile), take getline out of a while loop... call it once to get the first file, process it, then call it again and process the second file after the first one is done.

Alternatively, you could use break to exit the while loop as soon as datFile is done processing... but that isn't as sound logically.

Upvotes: 2

Boris Strandjev
Boris Strandjev

Reputation: 46943

Maybe something like:

int idx = 0;
while (getline(inFile, name))
{
    if (idx == 0)
    {
       datFile.open(name, ifstream::in);
       ...
    } else
    {
       ...
    }
    idx++;
}

Upvotes: 1

Related Questions