1
\$\begingroup\$

I have this following code to sort an array of strings order by ASCII value (alphabetically) using bubble sort.

#include <stdio.h>
#include <string.h>
int main(){
    char txt1[201][10], temp[201];
    for(int i=0; i < 10; i++){
        if(i){scanf("%c", txt1[i]);}
        scanf("%[^\n]s", txt1[i]);
    }

    for(int i=0; i<9; i++){
        for(int j=i+1; j<10; j++){
            if(strcmp(txt1[i], txt1[j]) > 0){
                strcpy(temp, txt1[i]);
                strcpy(txt1[i], txt1[j]);
                strcpy(txt1[j], temp);
            }
        }
    }
    for(int i=0; i < 10; i++){
        printf("%s\n", txt1[i]);
    }
}

Sample

> Input
Bravo
Charlie
Foxtrot
Alpha
Golf
Delta
Echo
Hotel
India
Juliet

> Output
Alpha
Bravo
Charlie
Delta
Echo
Foxtrot
Golf
Hotel
India
Juliet

But I have a concern at line 6-7 (In the first for loop). I need to input value with space so I used %[^\n]s (to receive a string with space) and %c (to receive space between each input).

Will it produce any problem when sorting if using this method on inputting the value?

\$\endgroup\$
  • \$\begingroup\$ Who or what text suggested an s in "%[^\n]s"? \$\endgroup\$ – chux Apr 4 at 2:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.