0

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!

Community
  • 1
  • 1
sdrtyrty rtyuty
  • 137
  • 1
  • 1
  • 8
  • 2
    Don't use `std::istream::eof` and use `std::getline` instead of `operator>>`. These go in the loop condition. Also, try `std::vector` instead of an array. Even more, you're reimplementing `std::string`'s `operator – LogicStuff Mar 04 '16 at 23:05
  • Sorry, I'm still new to this language. Could you be more specific about what to change. I don't see istream::eof. I know this is noob level. – sdrtyrty rtyuty Mar 04 '16 at 23:10
  • 1
    https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Baum mit Augen Mar 04 '16 at 23:11

1 Answers1

2

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.

Community
  • 1
  • 1
Weak to Enuma Elish
  • 4,531
  • 3
  • 22
  • 36