没有通过 getchar() 获取输入,或者在 do while 中可能出错?

Not taking input by getchar() or it might be error in do while?

我下面的程序没有使用 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');
}

你可以在a = getchar();

之前添加这个
getchar();

所以这个 'eats' 来自缓冲区的换行符。因为在您输入数字后,例如3 到 scanf("%d",&n); 缓冲区中仍然有一个 '\n',如果你只有这个:a = getchar();,\n 被读入

据参考:getchar()

Returns the next character from the standard input (stdin).

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

当在scanf("%d",&n);时你会输入一个int和一个换行符,然后getchar()只读取换行符

改用scanf("%d\n", &n);,或者如@BLUEPIXY所说,在a = getchar();

之前添加一个getchar();

关于输入缓冲区更详细的解释:Flush the input buffer