c - 在 c 中按字母顺序升序和降序对用户输入名称数组进行排序

标签 c arrays sorting

我是 C 的新手,有一个类(class)作业。我需要//构建一个程序,该程序使用一维数组来存储用户输入的 10 个名称。 //输入姓名后,用户应该会看到一个菜单,其中有两个选项可以按升序或降序对 10 个姓名进行排序和打印。

到目前为止我在这里

`

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char names[10][10];
    char temp[10],i,j;
    int count;
    int sort;
    count=1;
    for ((i=0);i<10;i++)
    {
        while (count<11)
        {
            printf("Please enter name %i\n",count);
            scanf("%s",names);
            count=count+1;
        }
    }
    printf("Would you like to print in Ascending (press 1) or Descending (press 2) order?\n\n");
    scanf("%d",&sort);
    switch (sort) {
        case 1:
            printf("\n Ascending order:\n ");


       printf("%s\n",names);
        qsort(temp, 10, 10, names);
        break;
    default:
    case 2:
        printf("\n Descending order:\n ");
        printf("%s\n",names);
        break;
}
        return 0;

我需要帮助弄清楚如何让它排序。

最佳答案

首先有一些错误:

1、一维数组不能存10个人名,需要二维数组,char names[10][10]即可.

2、当你使用qsort函数时,第四个参数是一个函数指针int (*cmp)(const void*, const void*) .

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp1(const void* l, const void* r)
{
    return strcmp((char*)l , (char*) r);
}
int cmp2(const void* l, const void* r)
{
    return -strcmp((char*)l , (char*) r);
}
int main()
{
    char names[10][10] = {0};
    char temp[10];
    int count;
    int sort;
    count=1;
    for (int i=0;i<10;i++)
    {
        printf("Please enter name %i\n",i+1);
        scanf("%s",names[i]);
    }
    printf("Would you like to print in Ascending (press 1) or Descending (press 2) order?\n\n");
    scanf("%d",&sort);
    switch (sort) 
    {
    case 1:
        printf("\n Ascending order:\n ");
        qsort(names, 10, 10, cmp1);
        break;
    case 2:
        printf("\n Descending order:\n ");
        qsort(names, 10, 10, cmp2);
        break;
    }

    for (int i = 0; i < 10; i ++)
    {
        printf("%s\n", names[i]);
    }
    return 0;
}

关于c - 在 c 中按字母顺序升序和降序对用户输入名称数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22999138/

相关文章:

c - 用文本替换占位符 - C?

c - 运行时错误 - 生成素数数组的代码

javascript - Lodash _.setWith 自定义路径

sorting - (快速)对 POSIX sh 中的文件列表进行排序

c - 确定网络接口(interface)是无线的还是有线的

c - 这段C语言代码有什么问题?

arrays - 如何在 Fortran 中即时增加数组大小?

JAVA:如何检查对象数组中的所有对象是否都是子类的对象?

python - 如何根据python中每行的前面数字将两个文件连接在一起

python - 使用 operator.itemgetter 对字典进行排序