-1
#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;
}
4

2 回答 2

3

\n从中删除scanf

  scanf(" %c%f%d\n",&name[i],&price[i],&pages[i]);    
           //   ^^ Remove it.   

使用\nin scanf,按下Enterscanf将跳过\n传递到输入缓冲区并期望非\n字符停止从输入缓冲区读取。

于 2015-04-07T13:35:01.667 回答
1

根据C11标准文档,第 7.21.5.2 章,fflush()功能,(强调我的)

int fflush(FILE *stream);

如果stream指向未输入最近操作的输出流或更新流,则该fflush函数会导致该流的任何未写入数据被传递到主机环境以写入文件;否则,行为未定义。

所以,基本上,fflush(stdin)调用未定义的行为

也就是说,正如@Hacks\n先生所提到的,您应该摆脱scanf().

于 2015-04-07T13:32:11.940 回答