Writing from one file to another.
Feb 21, 2015 at 2:06am UTC
I'm trying to take data from one file ("predata"), add the data together, and write those sums into another file ("postdata"). I can't seem to figure out how to use the while loop in the code. All help is appreciated.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
ifstream inputFile;
ofstream outputFile;
outputFile.open("predata.txt" );
outputFile<< 2 << "\t" << 9 << "\n" ;
outputFile<< 14 << "\t" << 8 << "\n" ;
outputFile<< 4 << "\t" << 21 << "\n" ;
outputFile<< 9 << "\t" << 12 << "\n" ;
inputFile.open("predata.txt" );
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int value6 = 0;
int value7 = 0;
int value8 = 0;
while (!outputFile.eof())
{
ifstream outputFile;
inputFile.open("postdata.txt" );
inputFile>> value1;
inputFile>> value2;
cout<< value1 << "\t" << value2 << "\t" << value1+value2 << "\n" ;
inputFile>> value3;
inputFile>> value4;
cout<< value3 << "\t" << value4 << "\t" << value3+value4 << "\n" ;
inputFile>> value5;
inputFile>> value6;
cout<< value5 << "\t" << value6 << "\t" << value5+value6 << "\n" ;
inputFile>> value7;
inputFile>> value8;
cout<< value7 << "\t" << value8 << "\t" << value7+value8 << "\n" ;
inputFile.close();
}
outputFile.close();
return 0;
}
Last edited on Feb 21, 2015 at 2:07am UTC
Feb 21, 2015 at 2:06pm UTC
You could simply open the same file for input and output, like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#include //every necessary headers
int main()
{
std::fstream ioFile( "in_out.txt" , std::ios::out );
//start writing to it manually like this below
ioFile << 9 << "\t" << 12 << "\n" ;
ioFile.close(); //although we can read w/o closing, I personally close it first.
int first_v {}, second_v{};
std::ostringstream ss{};
ioFile.open( "in_out.txt" , std::ios::in );
if ( ioFile ){ // if we successfully open it
while ( ioFile >> first_v >> second_v ) {
ss << first_v << " " << second_v << " " << ( first_v + second_v ) << "\n" ;
}
}
std::cout << ss.str() << std::endl;
std::ofstream out_file{ "out.txt" };
out_file << ss.str();
return 0;
}
Last edited on Feb 21, 2015 at 2:07pm UTC
Topic archived. No new replies allowed.