Hey guys, I'm having trouble writing into the file.
The purpose of my homework is to read numbers from a file, then write three numbers into that same file.
So far the reading part works then when it comes to writing to the file it just doesn't work , it like completely ignores the cin part
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
int numbers;
fstream outFile("results.txt", ios::in | ios::out);
if (!outFile)
{
cout << "File did not open \n";
exit(1);
}
cout << "Here are the numbers in the file: \n";
while (!outFile.eof())
{
outFile >> numbers;
cout << numbers << endl;
}
cout << "Enter three more numbers: \n";
for (int i = 0; i < 3; i++)
{
outFile << numbers <<endl;
}
cout << endl;
outFile.close();
return 0;
}
while (!outFile.eof()) Aside from fact that it is wrong and error-prone, after your loop finishes failbit and eofbit will be set on stream. Failbit in particulat means that all further read or write operations would fail automatically. You need to clear stream state. Also when you switch between reading/writing, you need to see to the position you want to read/write by seekp/seekg
Where would seekp() be written in the code?
My guess is before line 26.
Since I am using seekp() to write into the file would I have to use seekg() in the beginning of the code (line 19) to declare I am reading off from a file?
What is wrong with the while statement, I'm using eof() to extract the numbers that are in that file to be displayed.
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
int numbers;
ifstream inFile("PI.txt", ios::in | ios::out);
if (!inFile)
{
cout << "File did not open \n";
exit(1);
}
else
{
cout << "Here are the numbers in the file: \n";
while (!inFile.eof())
{
inFile >> numbers;
cout << numbers << endl;
}
inFile.close();
}
ofstream outFile ("PI.txt");
if (!outFile)
{
cout << "File did not open \n";
exit(1);
}
else
{
cout << "Enter three more numbers: \n";
for (int i = 0; i < 3; i++)
{
outFile << i <<endl;
}
cout << endl;
outFile.close();
}
return 0;
}