Hello guys. I am learn c++ on my own so i have quite a few questions. I appreciate all the helps from you guys. Today i have another question. Is the practice of associating two different ifstream object to a file safe? In the following code, I tried doing so. The compiler didn't seem to mind.
// Program to determine the median of a file which contains only sorted integers.
// Usage of array and vector isn't allowed.
#include <iostream>
#include <fstream>
#include <stdlib.h>
usingnamespace std;
int get_median(ifstream& in, ifstream& in1); // return the median of sorted file consisting of only integers.
int main()
{
int num;
ifstream infile, infile1;
infile.open("numbers.txt");
if(infile.fail())
exit(1);
infile1.open("numbers.txt");
if(infile1.fail())
exit(1);
cout << "median is: " << get_median(infile,infile1);
return 0;
}
int get_median(ifstream& in, ifstream& in1)
{
int num, counter = 0,counter1 = 0;
while(in >> num) // Compute the total number of integer in a sorted file
counter++;
in.close();
if(counter % 2 == 1) // return the median of file if the element counts in the file is odd.
{
while(in1 >> num)
{
counter1++;
if(counter1 == counter/2 +1)
return num;
}
}
if(counter % 2 ==0) // return the median of the file if the element counts is even
{ // There is some code repetition in the even and odd cases of element counts
while(in1 >> num) // They could probably be combined or put into a function.
{
counter1++;
if(counter1 == counter / 2)
{
int temp = num;
in1 >> num;
return(num+temp)/2.0; // Average of the two middle terms returned. A double isn't return here????????
}
}
}
}
For output streams since you can change the file with them it can be confusing where streams tend to append. Dangerous might be defined by confused output caused by that.
That said, consider seekg, a member function of ifstream. Using that you wouldn't need two streams, you could reuse one stream for both purposes.
Also, it isn't particularly good to close the stream in the function that reads from it. That happens automatically when the stream falls from scope at the end of the function that created it.