Search code examples
c++sortingtext-filesifstreamofstream

Trying to bubble sort a text file in C++


I need to create a program that reads a text file and shows its contents. I was only able to make my program to read the text file. However, i don't know how to call my function to sort the file. Is there a way to make its contents into a string for my function to sort it?

This is my program:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void bubble_sort(string arr[], int length)
{
    string temp;
    int iteration;
    int index;
    for (iteration=0; iteration<length; iteration++)
    {
        for (index=0; index<length-iteration; index++)
        {
            if (arr[index].compare(arr[index+1]) != 0)
                        {
                temp = arr[index];
                arr[index] = arr[index+1];
                    arr[index+1] = temp;
            }
        }
   }
}  

int main(void)
{
    ifstream file("list.txt");
    string str;
    string file_contents;

    while (getline(file, str))
    {
        file_contents += str;
        file_contents.push_back('\n');
    }

    cout << file_contents;
    return(0);
 }

This is the text file:

2 Witcher CdProjectRed 2015 9.3
4 Assassin Ubisoft 2013 8.3
5 Dragon Age Bioware 2014 8.5
3 Mass Effect Bioware 2013 8.9
1 Doom IDsoftware 2016 8.5

Solution

  • If you change file_contents from a string to a std::vector<string>, you will be able to operate on it in a similar fashion to how you would manipulate the contents of a plain-old-array. Storing all of your data in a single string (as you do in the code snippet you posted) makes sorting the substrings difficult (impossible?) because it's not obvious to the sort algorithm where one substring ends and the next one begins.