lle*_*eao 3 c sorting string alphabetical alphabetical-sort
好的,这是我的问题。老师必须随机选择一名学生(从她所拥有的学生中)以获得最终分数的特殊奖励,为此,她将 N 张编号从 1 到 N 的纸放入袋中并随机选择一个数字 K ; 获奖学生是学生名单中的第 K 个学生。问题是老师不知道哪个数字对应哪个学生,因为她丢失了包含这些信息的论文。她知道的是:所有学生的名字,以及他们的编号,从 1 到 N,按照字母顺序分配。
因此,我需要获取作为输入给出的一组姓名,按字母顺序对它们进行排序,然后提供获得特殊奖金的学生的姓名,但我在这样做时遇到了麻烦。我编写的程序对除第一个之外的所有名称进行排序。
此外,当我使用 Code::Blocks 运行项目时,会出现以下警告:
请告诉我我在这里做错了什么,以及是否有更好的方法来对名称进行排序而没有指定数量的名称。
注意:当 N 和 K 等于 0 时,程序应该停止读取输入。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int n, k, i, j=0, aux, numMenorNome;
char str[]="zzzzzzzzzzzzzzzzzzzz", str2[]="zwyxzzzzzzzzzzzzzzzz";
do
{
scanf("%d%d", &n, &k);
struct student
{
char nome[21]; /*name*/
char nomes_ordenados[21]; /*array to put the names already sorted*/
} s[n];
for (i=0; i<n; i++)
{
scanf(" %s", s[i].nome);
}
for (i=0; i<n; i++)
{
aux = strcmp(str, s[i].nome); /*compares the string that would be the last in the alphabetical order ("zzzzzzzzzzzzzzzzzzzz") with the given names*/
if(aux>0)
{
strcpy(str, s[i].nome); /*it gives me the name that comes first in alphabetical order */
numMenorNome = i; /* identification number of the name that was obtained */
}
if (i==(n-1))
{
strcpy(s[j].nomes_ordenados,str);
printf("%s\n", s[j].nomes_ordenados);
strcpy(str, "zzzzzzzzzzzzzzzzzzzz");
strcpy(s[numMenorNome].nome, str2);
j++;
i=0; /* restarts the loop in order to obtain the second name in alphabetical order, the third name, the fourth name and so on */
if(j==n)
break;
}
}
printf("%s\n\n", s[k-1].nomes_ordenados);
} while (n!=0&&k!=0);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
对字符串数组进行排序非常简单。只需使用qsort和现有的比较功能(即strcmp)
例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMES 5
#define NAME_LEN 10
void print_names(char names[][NAME_LEN])
{
int i;
for(i=0; i<NAMES; ++i)
{
printf("%s\n", names[i]);
}
}
int main(void) {
char names[NAMES][NAME_LEN] = { "xxx", "uuu", "ccc", "aaa", "bbb" };
print_names(names);
printf("---------------------------------\n");
qsort(names, NAMES, NAME_LEN, strcmp);
print_names(names);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22623 次 |
| 最近记录: |