0

I have the following code, i wanted to terminate the while loop if any key except 1 & 2 is press. but only do executes once. and not while. why my while condition is always false. please guide:

char a;

do
{
    printf("To Enter the Employee sales press 1 \n");
    printf("To Add more items press 2 \n ");
    printf("Press any key to Terminate \n\n");  

        scanf("%c", &a);
    if ( a == '1' )
    {
        printf("1 is presed ");
    }
    else if(a == '2')
    {
        int c;

        printf("entre Value:");
        scanf("%d",&c);
        printf("\n");
        addItem( &myArray, &size, c );
        printitems(myArray, size);   
    }
}while(a == '1' || a == '2');

Edit So sorry, it was in single qout. i forgot to put the latest code. Even with qoutes it does not run while.

Anton Dozortsev
  • 4,782
  • 5
  • 34
  • 69
Munsaf
  • 5
  • 3

2 Answers2

2

You need a space before your %c in scanf():

scanf(" %c", &a);

You're reading the first character that's entered and leaving one on the buffer. So if you enter:

'1' you're really getting two characters, first '1' then a '\n' (a "1" then a new line character, that happens when you hit enter). So it first stores '1' into a, then the second time it will read the remaining newline character into a, (it will apear to "skip" asking you for input). Since '\n' is not equal to '1' or '2' so it correctly exits.

Adding the space before the %c tells scanf() to ignore any white space left on the buffer (and new line characters count as white space)

Mike
  • 47,263
  • 29
  • 113
  • 177
  • Could not image in my wildest dreams about this. So much for ur time. i'm, feeling stupid. Thanks :) – Munsaf Feb 23 '14 at 14:53
1

You have declared 'a' as type char. and your while condition is


while(a == 1 || a == 2);


It should be


while(a == '1' || a == '2');

Alex
  • 21
  • 3
  • check that your addItem and printitems works perfectly. Without using those 2 function it works perfectly – Alex Feb 23 '14 at 14:51