Thread: How to write my sorted data to a new file. C++

  1. #1
    Registered User
    Join Date
    Nov 2022
    Posts
    6

    How to write my sorted data to a new file. C++

    So, I am trying to create a program to read a file, merge sort, output to a file and time the sorting. I have the code written for loading a file, sorting algorithm (borrowed from online and altered), creating a file all good to go. Unfortunately, what is sorted is not output to the new file. I'm new to C++ and all of this has been difficult, but I'm slowly learning. I know I need to take the sorted elements, increment them, and output to the new file, but can't seem to get it right tonight. I've basically confused myself.
    I have several files, problem1.cpp, merge_sort.cpp, and utilities.cpp. (header files and Makefile not included here)
    Any help would be appreciated, thanks so much!

    problem1.cpp:
    Code:
    #include <iostream>
    #include <fstream>
    #include <string>
    #include <vector>
    #include <chrono>
    #include "merge_sort.hpp"
    #include "utilities.hpp"
    using namespace std;
    
    
    int main(){
    
    
    cout << "\n========================================";
    cout << "\n\n Merge Sort Number Sorting Program...\n\n";
    cout << "=======================================\n\n";
    
      vector <double> input_data = getFile();
      int low = 0, high = (int)input_data.size()-1;
    
      cout <<"Sorting...\n";
    
              auto start = chrono::steady_clock::now();
    
       merge_sort(input_data, low, high);
    
              auto end = chrono::steady_clock::now();
              auto diff = end - start;
    
    cout << "Sorting completed in " << chrono::duration <double, milli> (diff).count() << endl;
    
    cout << "=======================================\n\n";
    cout << "Creating output file, named sorted_numbers.dat\n\n";
       createFile();
    
    /*this is where I run into trouble. Can't seem to figure this out. 
    How to get the sorted data into the new file. 
    I did this in C, but can't seem to translate it to C++. */
    
       vector<double> file_output;
       for (i = 0; i < (int)sorted.size(); i++)  {
           new_file << 
       }
    =======================================
    utilities.cpp: files for loading file and creating new file:

    Code:
    #include <iostream>
    #include "utilities.hpp"
    #include <vector>
    #include <fstream>
    
    
    //Get the file
    vector <double> getFile() {
        fstream loaded_file;
      vector <double> input_from_file;
        loaded_file.open("unsorted_numbers_short.dat", ios::in);
        if (!loaded_file.is_open()) {
            cout << "File not found!";
        }
        else {
    
    
        double temp;
    
    
            while (1){
                loaded_file >> temp;
            input_from_file.push_back(temp);
    
    
            if(loaded_file.eof())
                    break;
            }
            loaded_file.close();
        }
        return input_from_file;
    }
    
    
    void createFile(){
        fstream new_file;
        new_file.open("sorted_numbers.dat", ios::out);
      new_file << "TESTING \n\n";//just testing to see if it works. It does.
        if (!new_file) {
            cout << "File not created!";
        }
        else {
            cout << "File created successfully! \n\n";
        new_file.close();
        }
    }
    And the final bit of code, the Merge Sort:
    Code:
    #include <iostream>
    #include <vector>
    using namespace std;
    
    
    void merge(vector<double>, int, int , int );
    void merge_sort(vector<double> arr, int low, int high)
    
    
    //Helper sort for finding middle (from https://www.softwaretestinghelp.com/merge-sort/)
    {
        int mid;
        if (low < high){
            //divide the array at mid and sort independently using merge sort
            mid=(low+high)/2;
            merge_sort(arr,low,mid);
            merge_sort(arr,mid+1,high);
            //merge or conquer sorted arrays
            merge(arr,low,high,mid);
        }
    }
    // Merge sort
    void merge(vector<double> arr, int low, int high, int mid)
    {
        int i, j;
        vector<double> sorted;
    
    
        i = low;
        j = mid + 1;
        while (i <= mid && j <= high) {
            if (arr[i] < arr[j]) {
                sorted.push_back(arr[i]);
                i++;
            }
            else  {
                sorted.push_back(arr[j]);
                j++;
            }
        }
        while (i <= mid) {
            sorted.push_back(arr[i]);
            i++;
        }
        while (j <= high) {
            sorted.push_back(arr[j]);
            j++;
        }
        for (i = 0; i < (int)sorted.size(); i++)  {
            arr[i + low] = sorted[i];
        }
    }

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,426
    Code:
    void createFile(){
        fstream new_file;
        new_file.open("sorted_numbers.dat", ios::out);
      new_file << "TESTING \n\n";//just testing to see if it works. It does.
        if (!new_file) {
            cout << "File not created!";
        }
        else {
            cout << "File created successfully! \n\n";
        new_file.close();
        }
    }
    OK, you literally create the file and then immediately close it again.

    You need to return an opened file object back to main, so you can use it with your << operators to output data to the file.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2022
    Posts
    6
    Quote Originally Posted by Salem View Post
    Code:
    void createFile(){
        fstream new_file;
        new_file.open("sorted_numbers.dat", ios::out);
      new_file << "TESTING \n\n";//just testing to see if it works. It does.
        if (!new_file) {
            cout << "File not created!";
        }
        else {
            cout << "File created successfully! \n\n";
        new_file.close();
        }
    }
    OK, you literally create the file and then immediately close it again.

    You need to return an opened file object back to main, so you can use it with your << operators to output data to the file.

    Well, that was dumb of me. I'm trying to code while sick with the flu. Ok, so that solves part of the problem. The file I'm trying to sort has several hundred numbers in it. I need to output the sorted dat to the file and THEN close it.
    I have this so far (in int main()) and I know it's not right, but I'm going cross-eyed at this point.

    Code:
       createFile(input_data);
    
       int i;
       for (i = 0; i < (int)sorted.size()-1; i++)  {
           new_file << input_data << " ";
       }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,426
    Without all the createfile complication, which doesn't seem to add any value...

    This goes in main
    Code:
       fstream new_file.open("sorted_numbers.dat", ios::out);
       for (i = 0; i < (int)sorted.size(); i++)  {
           new_file << sorted[i] << endl;
       }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    Sep 2020
    Posts
    150
    Yor getFile could be simpler.
    Code:
    vector<double> getFile() {
      vector<double> input_from_file;
      fstream loaded_file("unsorted_numbers_short.dat");
      if (!loaded_file) {
        cout << "File not found!";
        return input_from_file;
      }
      double temp;
      while (loaded_file >> temp)
        input_from_file.push_back(temp);
    
      return input_from_file;
    }

  6. #6
    Registered User
    Join Date
    Nov 2022
    Posts
    6
    Quote Originally Posted by Salem View Post
    Without all the createfile complication, which doesn't seem to add any value...

    This goes in main
    Code:
       fstream new_file.open("sorted_numbers.dat", ios::out);
       for (i = 0; i < (int)sorted.size(); i++)  {
           new_file << sorted[i] << endl;
       }

    Thank you! This helped a lot. My merge code wasn't working properly, but once I got that working and I updated the main with your suggestion it worked!

  7. #7
    Registered User
    Join Date
    Nov 2022
    Posts
    6
    Quote Originally Posted by thmm View Post
    Yor getFile could be simpler.
    Code:
    vector<double> getFile() {
      vector<double> input_from_file;
      fstream loaded_file("unsorted_numbers_short.dat");
      if (!loaded_file) {
        cout << "File not found!";
        return input_from_file;
      }
      double temp;
      while (loaded_file >> temp)
        input_from_file.push_back(temp);
    
      return input_from_file;
    }
    Thank you! This works and looks a lot better than what I had, so I really appreciate it. I had to make changes to the merge code and all is working now, woohoo!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Read Input file, Calculate data, Write Output file
    By Ron09sime in forum C Programming
    Replies: 10
    Last Post: 07-04-2021, 02:17 AM
  2. How to convert/write data to XML file?
    By HiepDT in forum C Programming
    Replies: 4
    Last Post: 10-07-2011, 04:31 AM
  3. write data to end of file
    By sujeet1 in forum C++ Programming
    Replies: 2
    Last Post: 06-03-2007, 12:45 PM
  4. Write data to a disk file
    By bnd98 in forum C++ Programming
    Replies: 11
    Last Post: 04-20-2003, 04:21 PM
  5. Need to write data to file, not sure how
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 03-20-2002, 12:17 AM

Tags for this Thread