【问题标题】:Sort the array according to the alphabetic order of the last names of the students根据学生姓氏的字母顺序对数组进行排序
【发布时间】:2023-04-03 05:20:01
【问题描述】:

按照学生姓氏的字母顺序对数组进行排序,并将数组打印到控制台。

但是代码没有正确显示输出,为什么?

如果我提供意见。假设,

输入:

Enter the value of number: 2
Please enter the name of the student:
Nihan ahmed

输出:

After sorting the array:
Nihan ahmed

为什么我不能输入多个名字?

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<conio.h>
void main()
{   
    char name[10][8], temp[8];
    int i,j,n,L,k;
    printf("Enter the value of number:\n");
    scanf("%d", &n);
    fflush(stdin);
    printf("\n");
    printf("Please enter the name of the student:\n");
    for(i=0;i<n;i++)
    {
        gets(name[i]);
    }
    for(i=0;i<n-1;i++)
    {
        k=0;
        while(1)
        {
            ++k;
            if(name[i][k]==' ')
            break;
        }
        for(j=i+1;j<n;j++)
        {
           L=0;
           while(1)
           {
               ++L;
               if(name[j][L]==' ')
               break;
           }
            if(name[i][k+1]>name[j][L+1])
            {
               strcpy(temp,name[i]);
               strcpy(name[i],name[j]);
               strcpy(name[j],temp);
            }
        }
    }
    printf("After sorting the array:\n");
    for(i=0;i<n;i++)
    {
        puts(name[i]);
    }
    return 0;
}

【问题讨论】:

    标签: c arrays loops sorting


    【解决方案1】:

    你正在根据这个循环阅读 n 次:

    for(i=0;i<n;i++)
    {
       gets(name[i]);
    }
    

    这个循环正在做的是读取 10 个单词,当您编写 nihan ahmed 时,您正在存储 2 个字符串 name[0] 中包含 Nisan 并且 name[1] 中包含 Ahmed

    你需要做的(如果你不熟悉看起来像的结构)是:

    for(i=0;i<2*n;i++)
    {
       printf ("\n please enter the name of the student number %d: ", i);
       gets(name[i]);
    }
    

    【讨论】:

      【解决方案2】:

      这里:gets(name[i]); 有一些与从用户获取输入相关的限制。 我建议使用 scanf(" %s", name[i]) 。 如果你把 print 放在你的代码中

      for(i=0;i<n;i++)
      {
          printf("%d \n", i);
          gets(name[i]);
      }
      
      OUTPUT:
      Enter the value of number:
      2
      
      Please enter the name of the student:
      0 
      1 
      hello
      After sorting the array:
      
      hello
      

      你会发现在 0 -> (wait for input) -> 1 -> (wait for input) 的立场下,会同时出现 0, 1 个打印。

      如果您使用 scanf 来获取代码按预期工作。 请更改gets循环的代码:

      for(i=0;i<n;i++)
      {
          scanf("%s",name[i]);
      }
      
      OUTPUT:
      Enter the value of number:
      2
      
      Please enter the name of the student:
      hello 
      abcd
      After sorting the array:
      hello
      abcd
      

      【讨论】:

        猜你喜欢
        • 2020-09-10
        • 1970-01-01
        • 2013-11-30
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 2015-05-25
        相关资源
        最近更新 更多