Mustafa
Mustafa

Reputation: 590

Writing to file while reading from another file

Can we do both in a function, while using the elements of input file, can we write the results in output file same time?

inside of while statement is true?

void solve(string inputFileName, string outputFileName)
{
//declaring variables
string filename = inputFileName;

//Open a stream for the input file
ifstream inputFile;
inputFile.open( filename.c_str(), ios_base::in );

//open a stream for output file
outputfile = outputFileName;
ofstream outputFile;
outputFile.open(outputfile.c_str(), ios_base::out);

while(!inputFile.eof())
{
    inputFile >> number;    //Read an integer from the file stream
    outputFile << number*100 << "\n"
    // do something

}

//close the input file stream
inputFile.close();

//close output file stream
outputFile.close();
}

Upvotes: 3

Views: 3247

Answers (2)

Bo Persson
Bo Persson

Reputation: 92361

while(!inputFile.eof())

doesn't work very well, because it tests if the previous operation failed, not if the next one will be successful.

Instead try

while(inputFile >> number)
{
    outputFile << number*100 << "\n"
    // do something

}

where you test each input operation for success and terminate the loop when the read fails.

Upvotes: 2

Syntactic Fructose
Syntactic Fructose

Reputation: 20124

You can, the input and output stream are independent from each other, so mixing them together in statements has no combined effect.

Upvotes: 1

Related Questions