cstringscanfgets

Difference between "gets(s);" and "scanf("%s", s);" in C


I am writing a program that allows users to enter five names and sorts the names in Alphabet order, two adjacent names seperated by a newline character. Here is my code:

void sortWords(char s[][100], int n){
    int i, j;
    char *str;
    for(i = 0; i < n-1; i++){
        for(j = n- 1; j > i; j--){
            if(strcmp(s[j], s[j-1]) == -1){
                strcpy(str, s[j]);
                strcpy(s[j], s[j-1]);
                strcpy(s[j-1], str);
            }
        }
    }
}
int main(){
    char s[5][100];
    int i;
    for(i = 0; i < 5; i++){
        fflush(stdin);
        //gets(s[i]);      // when I use this statement, my program doesn't work
        scanf("%s", s[i]);
    }
    sortWords(s, 5);
    for(i = 0; i < 5; i++){
        printf("%s ", s[i]);
    }
    return 0;
}

When I changed the "scanf" in function main to "gets", after I have entered 5 names, the program just didn't print anything. Can anyone explain it for me, because normally, when I change one of them to the other function, I just have same results.


Solution

  • allows users to enter five names

    Names usually have a space between the parts of the full name. scanf("%s", s) does not read a full name, but only part of a name.

    Code has many other problems too.


    Difference between "gets(s);" and "scanf("%s", s);" in C

    One reads a line the other reads a word.

    Recommendations


    Other