954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Basic File I/O problem

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 median2.cpp (0.82KB)
Jeannie
Newbie Poster
1 post since Feb 2004
Reputation Points: 10
Solved Threads: 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.

Bob
Junior Poster
Team Colleague
129 posts since Feb 2003
Reputation Points: 15
Solved Threads: 2
 

how do u save an array into a file?

Big_D
Newbie Poster
1 post since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

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];
  }
}
Dogtree
Posting Whiz in Training
233 posts since May 2005
Reputation Points: 35
Solved Threads: 3
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You