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.

Recommended Answers

All 3 Replies

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.

how do u save an array into a file?

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];
  }
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.