0

What I have to do:
I have to read numbers from a file input from the keyboard into an array, sort the numbers, and write the sorted numbers to a file.

My problems are twofold:

First, I don't know how big to make the array. When I try to write the sorted numbers I can't get the junk numbers in my oversized array out of the way. I think that if I used a vector it would solve the problem, but I was specifically instructed to use a one dimensional array.

Second, I have to open the output file in function main, but I need to have at least four functions, and that entails writing to my output file in a separate function. I can get my compiler to okay the code, but it doesn't actually write to the file.

Assistance would be greatly appreciated. Thanks!

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Clinton Portis
0

1. How is the data arranged in your file? Please provide an example if that's not too much to ask.

2. A vector object can handle a file of infinite size and should be the container of choice for this project. Tell your instructor that a vector is an array.

3. Push your file into your vector array.

4. Sort your array as desired.

5. Create/open a new file to write to.

6. Write your vector to the new file.


You state that you are having difficulty writing to a file. It's as simple as creating on ofstream object, calling the open( ) function, and supplying a path/name/extention. Using the same ofstream object, use the << insertion operator to send data to the file. It's just like a cout << operation, just using a different stream.

Edited by Clinton Portis: n/a

0

if you want to pass a vector into a function, just prototype the parameter list just like you would any other data type; 'type' then 'var name':

//Pass by reference in order to directly modify the vector
void bubble_sort(vector<string>& file)
{
     bool is_swap = true;
     
     for(int i=0, size=file.size(); i<size && is_swap; i++)
     {
          is_swap = false;         

          for(int j=0; j<size-1; j++)
          {
               if(file[j] > file[j+1])
               {
                     swap(file[j], file[j+1]);
                     bool is_swap = true;
               }     
          }
     }
}

Edited by Clinton Portis: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.