不接受getchar()的输入,或者在执行时可能会出错?

时间:2015-01-25 16:07:22

标签: c do-while getchar

我的下面的程序没有使用getchar()进行输入。相反,它会在打印后结束"want to continue??(press y for yes and press n to reenter)"。输入nN后,它无法输入。

void main(){
    int i,arr[]={55,10,23,11,35,8,9,20},n;
    char a;
    printf("Given array is:\n");
    for(i=0;i<8;i++)
        printf("%d ",arr[i]);
        do{
            printf("\nEnter position where you want to insert element:");
            scanf("%d",&n);
            printf("You entered position %d \n",n);
            printf("want to continue ??(press y for yes and press n to reenter)");
            a=getchar();
        } while(a=='n' || a=='N');
}

2 个答案:

答案 0 :(得分:0)

根据参考:getchar()

  

返回标准输入(stdin)中的下一个字符。

请注意,标准输入是缓冲 I / O,因此getchar()读取输入缓冲区中的第一个字符

scanf("%d",&n);中输入int和换行符时,getchar()只读取换行符

使用scanf("%d\n", &n);,或者@BLUEPIXY说,在getchar();之前添加a = getchar();

有关输入缓冲区的更详细说明:Flush the input buffer

答案 1 :(得分:-1)

您可以在a = getchar();

之前添加此内容
getchar();

所以这'从缓冲区“吃掉”新行字符。因为输入一个例如3进入scanf("%d",&n);缓冲区中仍有一个'\n',如果您只有a = getchar();,则会在

中读取\ n