Search code examples
cdo-whilegetchar

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


My program below isn't taking input using getchar(). Instead, it ends after printing, "want to continue??(press y for yes and press n to reenter)". It doesn't take input after typing n or N.

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');
}

Solution

  • according to reference:getchar()

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

    Note that the standard input is a buffered I/O, so getchar() reads the first char in input buffer

    when in scanf("%d",&n); you will input an int and a newline, then getchar() just read the newline

    use scanf("%d\n", &n); instead, or as @BLUEPIXY said, add a getchar(); before a = getchar();

    more detailed explanations about input buffer: Flush the input buffer