#include <stdio.h>
#include <string.h>
typedef struct
{
char name[15];
int grade;
char major[15];
}studentRecord;
int main()
{
int m,i,j;
setvbuf(stdout,NULL,_IONBF,0);
printf("Please input the number of students(<=50):");
start:
scanf("%d",&m);
studentRecord student[m];
if(m<=50)
{
printf("Please input students'information:\n");
for(i=0;i<m;i++)
{
scanf("%s %d %s\n",student[m].name,&student[m].grade,student[m].major);
}
for(i=0;i<m-1;i++)
{
for(j=i+1;j<m;j++)
{
if(strcmp(student[i].name,student[j].name)>0)
{
char temp;
strcpy(temp,student[i].name);
strcpy(student[i].name,student[j].name);
strcpy(temp,student[j].name);
}
}
}
for(i=0;i<m;i++)
{
printf("%s %d %s",student[i].name,student[i].grade,student[i].major);
}
}
else
{
printf("Warning:Please input a number which does not exceed 50.\n");
printf("Input again:");
goto start;
}
修改如下,供参考:
#include <stdio.h>
#include <string.h>
#define N 50 //修改
typedef struct studentRec //修改
{
char name[15];
int grade;
char major[15];
}studentRecord;
int main()
{
int m, i, j;
studentRecord student[N] = { 0 }; //修改
setvbuf(stdout, NULL, _IONBF, 0);
printf("Please input the number of students(<=50):");
start:
scanf("%d", &m);
if (m <= 50)
{
printf("Please input students'information:\n");
for (i = 0; i < m; i++)
{
scanf("%s %d %s", student[i].name, &student[i].grade, student[i].major); //修改
//scanf("%s %d %s\n", student[m].name, &student[m].grade, student[m].major);
}
for (i = 0; i < m - 1; i++)
{
for (j = i + 1; j < m; j++)
{
if (strcmp(student[i].name, student[j].name) > 0)
{
studentRecord temp; //修改
temp = student[i]; //修改
student[i] = student[j];//修改
student[j] = temp; //修改
}
}
}
for (i = 0; i < m; i++)
{
printf("%s %d %s\n", student[i].name, student[i].grade, student[i].major);
}
}
else
{
printf("Warning:Please input a number which does not exceed 50.\n");
printf("Input again:");
goto start;
}
}