如何比较结构

时间:2018-05-21 18:50:56

标签: c

我有一个学校项目,我需要让用户选择按数字或字母顺序对两名学生进行排序。我已经设法做了第一个(数字顺序),但我无法理解我如何按字母顺序排序。

学生的名字由用户提供,并存储在结构中。当我尝试使用时:

if (strcmp((number_name_surname[0].name), (number_name_surname[1].name) < 0));

我得到错误'类型为“bool”的参数与“const char *”类型的参数不兼容。

这是结构

typedef struct
{
    int number;
    char name[10];
    char surname[10];
}num_nom_surname;
num_nom_surname *number_name_surname;

这是按字母顺序

if(number_name_surname[0].number > number_name_surname[1].number)
        { 
            for (i = number_of_students - 1; i >= 0; i--)
            {
                printf("\n Student N%c %5d - ", 167, number_name_surname[i].number);
                printf("Name: %s %s", number_name_surname[i].name, number_name_surname[i].surname);
            }
        }   
        else
        {
            for (i = 0; i < number_of_students; i++)
            {
                printf("\n Student N%c %5d - ", 167, number_name_surname[i].number);
                printf("Name: %s %s", number_name_surname[i].name, number_name_surname[i].surname);
            }
        }

这是我需要帮助的人

if (strcmp((number_name_surname[0].name), (number_name_surname[1].name) < 0));
        {

        }

//编辑//

所以现在我已经完成了,我有另一个问题。 为了按字母顺序打印名称,我需要确保名字不同。 例如:

如果名字是: Mark Adele ,第二个名字是: Mark Boy ,我该如何按顺序打印?

以下是代码:

if (strcmp((number_name_surname[0].name), (number_name_surname[1].name)) < 0) 
        {
            for (i = 0; i < number_of_students; i++)
            {
                printf("\n Student N%c %5d - ", 167, number_name_surname[i].number);
                printf("Name: %s %s", number_name_surname[i].name, number_name_surname[i].surname);
            }
        }
        else 
        {
            for (i = number_of_students - 1; i >= 0; i--)
            {
                printf("\n Student N%c %5d - ", 167, number_name_surname[i].number);
                printf("Name: %s %s", number_name_surname[i].name, number_name_surname[i].surname);
            }
        }
        printf("\n Value of strcmp: %d", strcmp((number_name_surname[0].name), (number_name_surname[1].name)));

2 个答案:

答案 0 :(得分:2)

您的括号已关闭,您已

if (strcmp((number_name_surname[0].name), (number_name_surname[1].name) < 0))

但你需要;

if (strcmp((number_name_surname[0].name), (number_name_surname[1].name)) < 0)

答案 1 :(得分:2)

如有疑问,请简化。

char* name1 = number_name_surname[0].name;
char* name2 = number_name_surname[1].name;

int res = strcmp(name1, name2);

if (res < 0)
{
   ...
}