Answer the question
In order to leave comments, you need to log in
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;
}
#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
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;
}
}
}
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.
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 questionAsk a Question
731 491 924 answers to any question