I am writing two program that go hand in hand for some assignments. The first program is to create a file and input an integer and a floating point value into it, using int value of 0 to close the file. The second program opens the file and reads the int and float values, and we can group them as pairs. Here is my basic code that does this almost completely right, but I don't understand why my program prints the last int and float value twice.
prog 1
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
int i;
float j;
ifstream file1; //declare the file variable
file1.open("CSC2134N.TXT"); //open the file for output
while(!file1.eof()) // loop until the end of the file is reached
{
file1 >> i >> j;
cout << i << ", " << j << endl;
}
file1.close(); // close file1
return 0;
}
Probably because you're using eof() to control the loop. The eof() condition is not set until after you read the file. I suggest something like:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
int i;
float j;
ofstream file("CSC2134N.TXT"); //open the file for output
while(file1 >> i >> j) // loop until no more data is read
{
cout << i << ", " << j << endl;
}
return 0;
}
And note, an ifstream is for input, not output. Use an ofstream for output. And there is no need to call the stream.close method, just let the destructor do it's job, and try to use the stream constructor whenever possible instead of calling the open member.
When I try to run this code it gives me an error at line 14 stating file1 isnt defined. After I changed line 11 to ofs tream file1("CSC2134N.TXT"); it says no match for 'operator>>' in 'file1 >> i'
I don't know why this instructor mentioned using the eof() as it seems thats a common problem. I only have a very basic understanding of this subject matter, as I am very new to it. This is an online class and my instructor literally teaches us nothing. Any more help on figuring this out would be awesome. Thanks for the tips so far!
After I changed line 11 to ofs tream file1("CSC2134N.TXT"); it says no match for 'operator>>' in 'file1 >> i'
It should in fact be ifstream file1 ... etc.
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
int i;
float j;
ifstream file1;
file1.open("CSC2134N.TXT");
while(file1 >> i >> j) // loop until no more data is read
{
cout << i << ", " << j << endl;
}
return 0;
}
After reading Chervil's comment and changing ofstream to ifstream, it appears to be working right. Thanks everyone for the help, and if there is anything I could have done better just let me know. This forum is very helpful and I am grateful.