Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22475

Why fgets() doesn't read after the first element?

$
0
0

I am trying to do this programming project in the book i study:

Write a program that sorts a series of words entered by the user:

Enter word: foo

Enter word: bar

Enter word: baz

Enter word: quux

Enter word:

In sorted order: bar baz foo quux

Assume that each word is no more than 20 characters long. Stop reading when the user enters an empty word (i.e., presses Enter without entering a word). Store each word in a dynamically sllocated string, using an array of pointers to keep track of the strings.

After all words have been read, sort the array (using any sorting technique) and then use a loop to print the words in sorted order.

That is what i am trying:

#include <stdio.h>
#include <string.h>

#define MAX_LENGTH 20

int compare ( const void * p, const void * q);

int main (void){
    int n;
    printf("How many words do you want to write");
    scanf("%d", &n);
    fflush(stdin);
    char * word[n];

    for( int i = 0; i < n; i++){
        fprintf(stdout , "Waiting for the word:");
       if(fgets(word[i] , MAX_LENGTH +1 , stdin) == "\n")
       break;
    }
    qsort((void *)word,n,sizeof(int),compare);

    printf("Ordered list is:\n\n");
    for( int i = 0; i < n; i++){
        fprintf(stdout , "\t %s", word[i]);
    }

}

int compare (const void * p, const void * q){
    return strcmp( * (char**) p , * (char **) q);
}

Edit : question with italic is solved thanks to fellow coders here. My new issue is i can't read past the first element of array. And program closes itself.

C:\Users\Lenovo\Desktop\ogrenme\ch17>sorting
How many words do you want to write4
Waiting for the word:asd

C:\Users\Lenovo\Desktop\ogrenme\ch17>

And there is one single annoying error that keeps me prevented from completing the exercise and "chill" with rest of this challenging book:

sorting.c:20:5: warning: implicit declaration of function 'qsort' [-Wimplicit-function-declaration]
    qsort((void *)word,n,sizeof(int),compare);

Viewing all articles
Browse latest Browse all 22475

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>