#include<stdio.h>
int main()
{
int i;
char name[3];
float price[3];
int pages[3];
printf("Enter names, price and no of pages of 3 books:\n ");
fflush(stdin);
for(i=0;i<=2;i++)
scanf(" %c%f%d\n",&name[i],&price[i],&pages[i]);
printf("And this is what you have entered:\n ");
for(i=0;i<=2;i++)
printf(" %c %f %d \n",name[i],price[i],pages[i]);
return 0;
}
Asked
Active
Viewed 39 times
-1

Sourav Ghosh
- 133,132
- 16
- 183
- 261

Sudip Modak
- 1
- 1
2 Answers
3
Remove \n
from scanf
.
scanf(" %c%f%d\n",&name[i],&price[i],&pages[i]);
// ^^ Remove it.
With \n
in scanf
, on pressing Enter, scanf
will skip the \n
passed to input buffer and expecting a non \n
character to stop reading from the input buffer.

haccks
- 104,019
- 25
- 176
- 264
1
As per C11
standard document, chapter 7.21.5.2, fflush()
function, (emphasis mine)
int fflush(FILE *stream);
If
stream
points to an output stream or an update stream in which the most recent operation was not input, thefflush
function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.
So, basically, fflush(stdin)
invokes undefined behaviour.
That said, as mentioned by Mr @Haccks, you should get rid of the \n
from the format string supplied in scanf()
.

Sourav Ghosh
- 133,132
- 16
- 183
- 261
-
Although C standard prohibits use of `fflush(stdin)` , it is well defined by some [libraries](https://msdn.microsoft.com/en-us/library/9yky46tz.aspx) and APIs. – haccks Apr 07 '15 at 13:43
-
@haccks Thank for sharing this info sir. However, to play safe (and portable), we shouldn't use `fflush(stdin)`. Please correct me if I am wrong. :-) – Sourav Ghosh Apr 07 '15 at 13:46
-
1I would say it is better to stick with C standard. – haccks Apr 07 '15 at 13:49
-
Thanks Sourav Ghosh and haccks for rectifying the mistake. – Sudip Modak Apr 16 '15 at 12:38