R
R
Retr0Hacker2022-02-20 23:01:00
C++ / C#
Retr0Hacker, 2022-02-20 23:01:00

How to sort structure data alphabetically?

Exercise
С клавиатуры ввести последовательность структур, содержащих данные о
результатах сессии студентов группы: <Фамилия, имя>, <Список рейтинговых
оценок>. Распечатать введенные данные в виде таблицы, отсортировав их по
фамилиями студентов в алфавитном порядке. Определить студентов с
самым высоким средним рейтинговым баллом.

My code
#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;
    }
}


But, alas, an error occurs: Error C4700 An uninitialized local variable "str" ​​was used.
Tell me how you can fix this problem or show another way to sort structures (qsort, alas, does not work)?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
W
Wataru, 2022-02-20
@wataru

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)

V
Vasily Demin, 2022-02-20
@includedlibrary

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];

A
Adamos, 2022-02-20
@Adamos

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 question

Ask a Question

731 491 924 answers to any question