我的循环只是安排第一个元素,我试着放一个外循环,但它不起作用。我需要在程序中使用另一个循环还是初始化另一个char数组[]来传输循环?

#include <stdio.h>
int main(void)
{
    char applicants[10][15],temp[15];
    char swap[10][15];
    int apps,i,j,c=0;

    printf("how many applicants?\n");
    scanf("%d",&apps);

    printf("enter the names of the applicants on seperate lines\n");
    printf("in order in which they applied for > ");
    for (i=0;i<apps;i++){
       scanf("%s",applicants[i]);
    }

    printf("\napplication order\n");
    printf("-----------------\n");
    for (i=0;i<apps;i++){
       printf("\t%s\n",applicants[i]);
    }

    for(i=0;i<apps-1;i++){
        c=strcmp(applicants[i],applicants[i+1]);
        printf("\n%d\n",c);
        if(c>0)
            strcpy(temp,applicants[i]);
            strcpy(applicants[i],applicants[i+1]);
            strcpy(applicants[i+1],temp);
    }

    printf("\n\n alphebatize order\n");
    printf("-------------------\n");
    for (i=0;i<apps;i++){
       printf("\t%s\n",applicants[i]);
    }


if(strcmp(applicants[0],applicants[1])>0){
        printf("\n\n%s is greater than %s",applicants[0],applicants[1]);
    }


}

最佳答案

您的if语句缺少括号

if(c>0)
    strcpy(temp,applicants[i]);
    strcpy(applicants[i],applicants[i+1]);
    strcpy(applicants[i+1],temp);

意思是一样的
if (c > 0)
 {
    strcpy(temp, applicants[i]);
 }
strcpy(applicants[i], applicants[i + 1]);
strcpy(applicants[i + 1], temp);

因此,您要用applicants[i]覆盖applicants[i + 1],然后将存储在applicants[i + 1]中的前一个值写入temp,这不一定是applicants[i]
你需要加上大括号
if (c > 0)
 {
    strcpy(temp, applicants[i]);
    strcpy(applicants[i], applicants[i + 1]);
    strcpy(applicants[i + 1], temp);
 }

08-17 17:43