Search code examples
cstdinfgets

how can I read multiple inputs from stdin in c using fgets


I tried this code and the wrote another similar one to read another input but the program read in the second time both the first stdin and the second one (also I used fflush(stdin) instead of fseek() but that didn't work either)

     int BUFFERSIZE=100;
     char input[BUFFERSIZE];
     char *final=malloc(1);
     while(fgets(input,BUFFERSIZE-1,stdin))
     {
         final=realloc(final,strlen(final)+strlen(input)+1);
         strcat(final,input);
         if(input[strlen(input)-1]=='\n') break;

     }
     sscanf(final,"%d",&opt);
     free(final);
     fseek(stdin,0,SEEK_END);

Solution

  • You didn't initialize the contents of the final buffer before the loop. So the first strlen(final) and strcat(final, input) are reading an uninitialized string, causing undefined behavior.

         int BUFFERSIZE=100;
         char input[BUFFERSIZE];
         char *final=malloc(1);
         *final = 0; // initialize to empty string
         while(fgets(input,BUFFERSIZE-1,stdin))
         {
             final=realloc(final,strlen(final)+strlen(input)+1);
             strcat(final,input);
             if(input[strlen(input)-1]=='\n') break;
    
         }
         sscanf(final,"%d",&opt);
         free(final);