-2

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');
}
wolfPack88
  • 4,163
  • 4
  • 32
  • 47

2 Answers2

0

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

simon_xia
  • 2,394
  • 1
  • 20
  • 32
-1

You can add this before a = getchar();

getchar();

So this 'eats' the new line character from the buffer. Because after you entered a number e.g. 3 into scanf("%d",&n); there is still a '\n' in the buffer and if you only have this: a = getchar();, \n gets read in

Rizier123
  • 58,877
  • 16
  • 101
  • 156