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);
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.