sdrtyrty rtyuty
sdrtyrty rtyuty

Reputation: 147

How to sort by line only, NOT by line and/or space in C++

I've created a program to sort everything in a text file in alphabetical order. However if 2 or more words on the same line have a space between them it will recognize them as being separate. I want to prevent this.

I'm trying to make it ONLY sort lines. So for example:

Orange Soda

Pepsi

Coca Cola

to become......

Coca Cola

Orange Soda

Pepsi

NOT......

Coca

Cola

Orange

Pepsi

Soda

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){

    ifstream sortFile("list.txt");
    string theArray[9999], temp;
    int count=0, x, y;

    if(!sortFile.is_open()){
        cout << "Cannot find \"list.txt\" in the current directory." << endl;
    }

    // determine how many separate list items
    while(!sortFile.eof()){
        sortFile >> theArray[count];
        count++;
    }// while

    // arrange array in alphabetical order
    for(x=0;x<count;x++){
        for(y=0;y<count;y++){
            if(theArray[x]<theArray[y]){
                temp = theArray[x];
                theArray[x] = theArray[y];
                theArray[y] = temp;
            }// if
        }// for y
    }// for x

    // save to file
    ofstream saveFile("fixed.txt");
    for(x=0;x<count;x++){
        if(theArray[x]!=theArray[x+1]){
            if(count-1==x){
                saveFile << theArray[x];
            }else{
                saveFile << theArray[x] << endl;
            }// if else
        }else{
            saveFile << theArray[x] << " ";
        }// if else
    }// for

    saveFile.close();
    cout << "Completed Sucessfully! Look for a file named \"fixed.txt\"";

    cin.get();
}

Thanks in advance!

Upvotes: 0

Views: 142

Answers (1)

Weak to Enuma Elish
Weak to Enuma Elish

Reputation: 4637

Replace your while loop with this:

while(std::getline(sortFile, theArray[count++]));

The >> operator for streams delimits at white space, but getline will read the whole line.

Additionally, using eof in a loop condition is BadTM.

Upvotes: 2

Related Questions