【发布时间】:2020-03-14 02:10:00
【问题描述】:
我有一个项目,我必须创建一个程序,让用户以任何顺序输入姓名。然后程序按字母顺序显示名称。此外,所有这些都必须使用指针来完成。现在我对程序的尝试提示用户输入名称并显示它们,但由于某种原因我无法对其进行排序。有人可以帮我吗?
这是我对该程序的尝试:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
int list;
char *names[20];
char str[20];
printf("Enter the number of names: ");
scanf("%d", &list);
fflush(stdin);
for (int i = 0; i < list; i++) {
printf("Enter name %d: ", i + 1);
// gets(str);
scanf("%[^\t\n]s", str);
fflush(stdin);
names[i] = (char *)malloc(strlen(str) + 1);
strcpy(names[i], str);
}
void sortNames();
for (int i = 0; i < 5; i++)
printf("%s\n", names[i]);
return 0;
}
void sortNames(char **name, int *n) {
int i, j;
for (j = 0; j < *n - 1; j++) {
for (i = 0; i < *n - 1; i++) {
if (compareStr(name[i], name[i + 1]) > 0) {
char *t = name[i];
name[i] = name[i + 1];
name[i + 1] = t;
}
}
}
}
int compareStr(char *str1, char *str2) {
while (*str1 == *str2) {
if (*str1 == '\0' || *str2 == '\0')
break;
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0')
return 0;
else
return -1;
}
【问题讨论】:
-
我假设您出于教学原因正在编写自己的
compareStr函数,但如果您不是,您可能希望使用strcmp(来自string.h)来代替。 -
你不能用
qsort吗?还是需要您编写自己的排序函数? -
@kopecs 是的,我正在编写自己的 compareStr,这是一个要求。
-
@TomKarzes 我得自己写排序函数
-
我不清楚您为什么将
n作为sortNames中的指针。还值得注意的是,您的compareStr函数永远不会返回 1。str1更大的预期处理是什么?
标签: c sorting pointers string-comparison