read from data.txt file and write to results.txt in c drive.
here is the data.txt file (didn't press enter after number 5):
3
4
5
everything runs but the output repeats the number 5
Here are the numbers in the file:
3
4
5
5
Press any key to continue . . .
and in the results.txt file the only number outputted is the number 5
here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int num;
ifstream inFile;
ofstream outFile;
inFile.open("data.txt");
if (! inFile)
{
cout << "ERROR - File did not open!\n";
exit(1);
}
cout << "Here are the numbers in the file: \n";
while(!inFile.eof())
{
inFile >> num;
cout << num << '\n';
}
outFile.open("c:\\result.txt");
if(outFile.fail())
{
cout << "ERROR - File did not open!\n";
system("pause");
return 1; /// or return 1
}
cout << endl << endl;
outFile << num;
inFile.close();
outFile.close();
system("pause");
return 0;
}
Thank you
@TheJJJunk
but now in the c drive the result.txt file doesn't include the
3
4
5
it just shows:
5
how do i make the 3 4 and 5 show?
Because you have outFile << num;
and it's not in a loop, so it will only send the last value that was assigned to num. In this case 5.
You could assign 3, 4, and 5 to different variables? and then send them all back.
Last edited on
i can't specifically extract the numbers from data.txt
instead of creating variables
int a = 3;
int b = 4;
int c = 5;
creating a loop? but how? would i have to create a function?
Last edited on