Hi!
I want to create a program which writes on a file an array of integers and then returns the highest value of this array. I'm showing you the code , CAN SOMEBODY TELL ME WHERE IS THE PROBLEM?
Thank you!
P.S:: I expect to it to return 4 but when i run it it returns -5.
Use ofstream to write to a file, and ifstream to read from file.
You can use fstream to do both.
A few things, Alendrex. You need to set up your fstream to work with both the input and output stream:
data.open(filename.c_str(), ios::out | ios::in); // in main
Because you'll be using it for input in your read_data function.
The reason why your returning -5 all the time is because your file stream is at the end of the file since it just finished writing to it and needs to be set back to the beginning, so do this:
in.seekg(ios::beg); // in read_data
Lastly, fstream::fail() doesn't specifically error for opening the file. You'll want to use fstream::is_open() and you'll want to check that before you try writing to it.
If you leave out that parameter it does that by default...
Ah, didn't realize that.
The istream and ostream pointers are independent of each other in my testing.
Copying Alendrex's code and accounting for both input and output, I get the same exact result as him until I reset to the beginning of the file. *messes with fstream some more*
Huh, I didn't know that, sorry. I guess my testing was different somehow...I'll jave to do some more testing to determine what I originally did...look at me still talking when there's testing to do.