T
T
Timofey Lanevich2016-05-11 07:18:30
C++ / C#
Timofey Lanevich, 2016-05-11 07:18:30

Sorting in a file?

Unable to sort data in file names alphabetically. But for me it's all right.
Structure :

#pragma once
#include <iostream>

using namespace std;

struct database{
    char myName[124];
    char city[124];
  int age;
};

database recordIn(){
  database infa;
  cin.ignore();
  cout << "Name : ";
    cin >> infa.myName;
  cout << "City : ";
  cin >> infa.city;
  cout << "Age : ";
  cin >> infa.age;
  return infa;
}

Sorting itself:
#pragma once
#include <fstream>
#include <cstring>
#include "structRecord.h"

using namespace std;

void sortFile(){
    fstream f("test.txt", ios::in | ios::binary);
    fstream f1("tes.txt", ios::out | ios::binary);
    database infa;
    database mas[124];
    int i=0;
    while(f.read((char*)&mas[i],sizeof(database))!= NULL){
        i++;
    }
    int n=i;
    for(int i=0; i<n; i++){
        for(int j=0; j<n; j++){
            if(strcmp(mas[j].myName, mas[j+1].myName) >0){
                infa=mas[j+1];
                mas[j+1]=mas[j];
                mas[j]=infa;
            }
        }
    }
    for(int i=0; i<n; i++){
        f1.write((char*)&mas[i],sizeof(database));
    }
f1.close();
    f.close();
    remove("test.txt");
    rename("tes.txt","test.txt");
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
T
Timofey Lanevich, 2016-05-12
@Timak31

Answer to the question

for(int i=0; i<n; i++){
        for(int j=0; j<n-1; j++){
            if(strcmp(mas[j].myName, mas[j+1].myName) >0){
                infa=mas[j+1];
                mas[j+1]=mas[j];
                mas[j]=infa;
            }
        }
    }

R
Rsa97, 2016-05-11
@Rsa97

Sorting is, of course, inefficiently implemented and there is an exit from the array, but it seems to work.
So run the debugger and see what happens step by step. Or add the output of the necessary information to the loop and monitor the program's work.

J
JoyceGraham, 2016-05-11
@JoyceGraham

Well, the first thing that catches your eye is going beyond the array at j + 1 for j = n - 1. It's strange that it doesn't fall

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question