Home > Back-end >  Sorting strings from file to new file
Sorting strings from file to new file

Time:11-08

This is my function to get lines from file to strings

void getStringsFromFile() {
    ifstream database;
    database.open("Database.txt", ios::app | ios::in | ios::binary);

    if (!database) {
        cout << "Kunne ikke indlaese filen..." << endl;
    }
    int count = 0, c = 0;
    string getString, tmp, str[256];
    for (int i = 0; i < 5; i  ) {
        while (getline(database, getString)) {
            str[i] = getString;
            cout << "String: [" << count   << "] " << str[i] << endl;
        }
    }
    sortStrings(getString);
}

This is how I'm saving my data to .txt file

     if (database.is_open()) {
         database << list[i].navn << "\t" << list[i].addresse << "\t" << list[i].alder << "\t" << list[i].tlf << "\t" << "\n";
         database.close();

It outputs like this: line 0 is empty

Kasper Jensen   
Jomfrugade 5    21  44556677

Victor Hansen   
Østergade 94    25  54644773

I have this function to sort the strings, ascending by insertion. It don't work with string to char

void sortStrings(string &lines) {
    string* lines = nullptr;
    string temp;
    int count;

    for (int i = 0; i < count - 1; i  ) {
        for (int j = 0; j >= 0; j--) {
            if (lines[j] > lines[j   1]) {
                temp = lines[j];
                lines[j] = lines[j   1];
                lines[j   1] = temp;
            }
        }
    }
}

I want my code to grab relevant lines from one .txt file and sort it to another. I dont really care which sorting method

I have problems with it recognizing the right strings and grabbing them and outputting them into new file

CodePudding user response:

The getStringsFromFile function will read all lines from the file, and put them all into str[0]. Then the sortStrings function will attempt to sort a single string. There are other things that looks weird as well.

What I recommend you to do, is to create a vector of strings, read lines in a loop (the while (getline(...)) loop) and add to the vector, then use the standard std::sort function to sort the vector.

Once that's done you can write the strings in the vector to a new file.


Note that the above assume that there's no specific format in the file, that each line is its separate record. If your file have a specific multi-line record format then that won't work.

If this is the case then I recommend you create a class for the records, implement a stream extract operator for the class (operator>> for std::istream), and use a loop (while (file >> my_record_object)) to read all records into a vector.

Then again sort the vector using std::sort, using a suitable ordering function (lambda or overloaded operator< function for the class). Then write the data in the vector to the new file using an overloaded operator<< function.

  •  Tags:  
  • c
  • Related