一个c语言问题要求设计一个程序可以输出人名按字母顺序排序

# include "stdio.h"
# include "conio.h"
# include "string.h"
# define BUFFSIZE 100
main()
{
int m;
printf("please input the quantities of the students\n");
scanf("%d",&m);
char name[m][10],buff[BUFFSIZE];
int i,j,k,n;
for(i=0;i<m;i++)
{
printf("please input the name of the %dth students",i+1);
gets(buff);
if(strlen(name)>10)
{
printf("the name you input is larger than 10\n");
continue;
}
strcpy(name[i],buff);
}
for(j=0;j<m;j++)
{
for(i=0;i<m-j;i++)
{
if(name[i]>name[i+1])
{
strcpy(buff,name[i]);
strcpy(name[i],name[i+1]);
strcpy(name[i+1],buff);
}
这个那里有错误怎么改?
}
}
for(i=0;i<m;i++)
printf("%s\n",name[i]);
}

已经修改好了:

# include "stdio.h"

# include "conio.h"

# include "string.h"

# define BUFFSIZE 100

main()

{

int m,i,j,k,n;

char name[100][10],buff[BUFFSIZE];

printf("please input the quantities of the students\n");

scanf("%d",&m);

fflush(stdin);        /*要清除缓冲区*/

for(i=0;i<m;i++)

{

printf("please input the name of the %dth students:",i+1);

gets(buff);

while(strlen(name)>10)        /* 当长度>10时重新输入 */

{

printf("the name you input is larger than 10\n");

printf("please input the name of the %dth students:",i+1);

gets(buff);

}

strcpy(name[i],buff);

}

for(j=0;j<m-1;j++)

{

for(i=0;i<m-j;i++)

{

if(strcmp(name[i],name[i+1])>0)        /* 比较字符串的大小 */

{

strcpy(buff,name[i]);

strcpy(name[i],name[i+1]);

strcpy(name[i+1],buff);

}

}

}

for(i=0;i<m;i++)

printf("%s\n",name[i]);

}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-03-14
错还不少, 把中文删除了再编译。
#include <stdio.h>  标准头文件使用尖括号
#include <string.h>

#define BUFFSIZE 100
#define MAX_PEOPLE 100 数组只能静态申请,固定大小。
#define MAX_NAME 10

int main(void)
{
int m;
printf("please input the quantities of the students\n");
scanf("%d",&m);

char name[MAX_PEOPLE][MAX_NAME]; 数组只能静态申请,固定大小。
char buff[BUFFSIZE];

int i,j; 无用的变量应删除。
for( i=0; i<m; i++)
{
printf("please input the name of the %dth student",i+1);
scanf("%s", buff); 只输入名字,比较适合用scanf,不会有\n.
if(strlen(buff) > 10) 这里只应对buff判断长度
{
printf("the name you input is larger than 10\n");
continue;
这里实际是上不对,因为continue后,i会加一,name
数组中就有一个名字未赋值。
不过,原程序没有更好的处理思路。
}
strcpy(name[i], buff); 这才移到
}

字符串交换的操作比较费时,最好使用选择排序,可以减少交换的次数。
for(j=0;j<m;j++)
{
for(i=0;i<m-j-1;i++) 关键错误多循环一次,只应有m - 1 - j,比如
j为0时,i 最后一次为m - 2,i + 1是m - 1
{
if(strcmp(name[i], name[i+1]) > 0) 字符串不能直接比较,要通过函数strcmp
{
strcpy(buff,name[i]);
strcpy(name[i],name[i+1]);
strcpy(name[i+1],buff);
}
}
}
for(i=0;i<m;i++)
printf("%s\n",name[i]);
}

相似回答