我正在编写一个程序来按字母顺序输入姓名和年龄。年龄是单独输入的,所以我知道我需要使用一个指针数组来将年龄与名字数组联系起来,但我无法弄清楚如何去做。有什么想法吗?
到目前为止,我的程序只按字母顺序排列名称。
/* program to alphabetize a list of inputted names and ages */
#include <stdio.h>
#define MAXPEOPLE 50
#define STRSIZE
int alpha_first(char *list[], int min_sub, int max_sub);
void sort_str(char *list[], int n);
int main(void)
{
char people[MAXPEOPLE][STRSIZE];
char *alpha[MAXPEOPLE];
int num_people, i;
char one_char;
printf("Enter number of people (0...%d)\n> ", MAXPEOPLE);
scanf("%d", &num_people);
do
scanf("%c", &one_char);
while (one_char != '\n');
printf("Enter name %d (lastname, firstname): ", );
printf("Enter age %d: ", );
for (i = 0; i < num_people; ++i)
gets(people[i]);
for (i = 0; i < num_people; ++i)
alpha[i] = people[i];
sort_str(alpha, num_people);
printf("\n\n%-30s5c%-30s\n\n", "Original List", ' ', "Alphabetized List");
for (i = 0; i < num_people; ++i)
printf("-30s%5c%-30s\n", people[i], ' ', alpha[i]);
return(0);
}
int alpha_first(char *list[], int min_sub, int max_sub)
{
int first, i;
first = min_sub;
for (i = min_sub + 1; i <= max_sub; ++i)
if (strcmp(list[i], list[first]) < 0)
first = i;
return (first);
}
void sort_str(char *list[], int n)
{
int fill, index_of_min;
char *temp;
for (fill = 0; fill < n - 1; ++fill){
index_of_min = alpha_first(list, fill, n - 1);
if(index_of_min != fill){
temp = list[index_of_min];
list[index_of_min] = list[fill];
list[fill] = temp;
}
}
}
答案 0 :(得分:1)
您的大多数printfs都是语法错误,如
printf("Enter name %d (lastname, firstname): ", );
printf("Enter age %d: ", );
或立即炸弹,因为你传递一个int(' '
)作为指针:
printf("\n\n%-30s5c%-30s\n\n", "Original List", ' ', "Alphabetized List");
首先,让所有你的%
向右,向我们展示你真正编译的内容,而不是随机垃圾。并将编译器的警告级别调到最大,你需要它!什么是
#define STRSIZE
应该意味着什么时候STRSIZE
被用作arary维度?你会遇到严重的剪切和粘贴问题。
答案 1 :(得分:0)
创建结构可能更容易:即
struct person {
char name[STRSIZE];
int age;
}
否则,如果您必须按照尝试的方式进行,只需创建一个额外的索引数组。移动名称时,还可以移动数组上的索引...完成名称排序后,只需对年龄进行排序以匹配索引。