0
votes

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);
1
You can't seek in stdin unless it's redirected to a file.Barmar
Note: -1 not needed in fgets(input,BUFFERSIZE-1,stdin). Suggest fgets(input, sizeof input, stdin).chux - Reinstate Monica

1 Answers

0
votes

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);