char - C program skips a line when asking for user input -
this question has answer here:
printf("number of tracks: "); fflush( stdin ); scanf("%d", &track); printf("is album or single: "); fflush( stdin ); scanf("%c", &type); when entered 5 number of track, program displays album or single , ends program there without letting me enter album type?
point 1
do not use fflush( stdin );, undefined behaviour.
related: c11 standard docmunet, chapter 7.21.5.2, (emphasis mine)
int fflush(file *stream);if
streampoints output stream or update stream in recent operation not input, fflush function causes unwritten data stream delivered host environment written file; otherwise, behavior undefined.
point 2 (to work done suppossed done fflush(stdin))
change
scanf("%c", &type); to
scanf(" %c", &type); ^ | the leading whitespace ignores whitespace-like characters in buffer , reads first non-whitespace character stdin.
Comments
Post a Comment