简体   繁体   中英

sorting a 2d string array by alphabetizing in c

my loop is only arranging the first element, i tried putting an outer loop but it is not working. do i need another loop within my program or initialize another char array[] to transfer the loop?

#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]);
    }


}

Your if statement lacks braces here

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

this means the same as

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

so you are overwriting applicants[i] with applicants[i + 1] and then writing to applicants[i + 1] the previous value that was stored in temp , which is not necessarily applicants[i] .

You need to add braces

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM