Answer the question
In order to leave comments, you need to log in
How to sort structure data alphabetically?
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string.h>
using namespace std;
struct Student
{
char familia[20];
int exam;
};
void main()
{
Student sot[128];
int i, j, a, m;
char* str;
cout << "Введите количество студентов: ";
cin >> a;
for (i = 0; i < a; i++)
{
cout << "\nФамилия " << i + 1 << "-ого студента: ";
cin >> sot[i].familia;
cout << "\nРезультаты сессии: ";
cin >> sot[i].exam;
}
for (j = 0; j <= a; j++)
{
for (i = 1; i < a; i++)
{
if (strcmp(sot[i - 1].familia, sot[i].familia) > 0)
{
strcpy(str, sot[i - 1].familia);
strcpy(sot[i - 1].familia, sot[i].familia);
strcpy(sot[i].familia, str);
}
}
}
for (i = 0; i < a; i++)
{
cout << sot[i].familia << endl;
cout << sot[i].exam << endl << endl;
}
}
Answer the question
In order to leave comments, you need to log in
You have a str variable, and as the compiler tells you, you do not initialize it with anything. And below use in . This function takes a pointer to the memory area where the string should be copied. But the pointer points to a random place. Those. the program, even if miraculously compiled, will crash with an exception.
You either need to allocate memory for str via malloc, or declare str as a fixed-size char array, like the familia field of a structure. strcpy(str, sot[i - 1].familia)
Use type
If you use a pointer, as you are doing now, you need to initialize it, otherwise strcpy will copy it to God knows where (but most likely it will just be segfault)
char str[20];
What does C have to do with it if using namespace std is declared first?
If the standard library is still used, why the hell are these char and dancing with a tambourine?
std::string for strings
std::sort for sorting (adding a string comparison callback) or std::swap if you prefer the cycling algorithm.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question