I'm pretty new at C++ and I have a problem with a program that opens a file with a list of numbers and finds the median. My problem is, no matter what numbers are in the file, it always says the median is 1. I've been able to tell it what position the median is in, but I can't get it to return the number that's in that position. How can I get it to reopen the file, find the median number, and spit it back to me?

Attached is what I've done so far.
Here is what the data file is uses looks like:
file2.dat
1
2
3
4
5
6
7
8


I know the simplicity of it is laughable, but bear with me. I'm a newbie.

Attachments
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main ( )
{
	ifstream in_stream;
	ofstream out_stream;
	int next, count=0, median, median_position;

	in_stream.open("file2.dat");
		if (in_stream.fail( ))
		{
			cout << "Input file opening failed.\n";
			exit(1);
		}

		while (in_stream >> next)
		{
			count++;
		}

	in_stream.close( );
	in_stream.clear( );
	
	if ((count%2) != 0)    //if the count is odd
	{
		median = ((count/2) + 1);
	}
	else
	{
		median_position = (count/2);
		median = ((median_position + next)/2);
	}

	in_stream.open("file2.dat");
	
		if (in_stream.fail( ))
		{
			cout << "Input file opening failed.\n";
			exit(1);
		}

		in_stream >> median;

	cout << "The median is " << median << ".\n";

	in_stream.close( );

	return 0;

}

Hi, don't worry, it's not laughable, we've all been equally as stumped with problems equally as simple once upon a time.

Having calculated which position the median is at, you then reopen the file, read in the first value from the file, and output this as the median. The first value in the file is 1, so the program always outputs this as the median, even though it's not the value in the median position.

You need to read in values until you've reached the one at the median position, rather than just reading in the first value.

Hope that helps.

Dude, this thread is well over a year old. Next time, if you have a new question, start a new thread.

To save an array to file, just open the file, then loop over the array and write each element in turn:

#include <fstream>

int main()
{
  std::ofstream out("somefile");
  int array[] = {0,1,2,3,4,5,6,7,8,9};

  if (out.is_open()) {
    for (int i = 0; i < 10; i++)
      out << array[i];
  }
}
This article has been dead for over six months. Start a new discussion instead.