简体   繁体   中英

While Loop skipping scanf for it's condition.

I can't see why does the While loop just speed away and skipping the scanf for the char? It would not even ask for my input and just loop like there's no tomorrow.

#include <stdio.h>


int main()
{
    int number;
    int multiply, ans;
    char choice;

    printf("-------------------------------------");
    printf("\n      MULTIPLICATION TABLE           ");
    printf("\n-------------------------------------");


    do
    {

         printf("\nEnter an integer number:");
         scanf("%d", &number);


        printf("\nMultiplication of %d is :-\n", number);
        printf("\n");

        for(multiply=1; multiply<11; multiply++){
            ans = number * multiply;
            printf(" %d", ans);
        }

        printf("\n");
        printf("\nWould you like to continue? [Y] for Yes,[N] for no : ");
        scanf("%c", &choice);
        printf("\n");

    } 
    while(choice='Y');

    printf("Thank You");
    return 0;

}

scanf() doesn't do what you think it does (newline characters, buffering, etc.). It's preferred to use fgetc() :

choice = fgetc(stdin);

For the same reason, you need to get rid of the trailing newline that

scanf("%d", &number");

leaves in the standard input buffer. To fix this, insert

fgetc(stdin);

after that particular call to scanf() .

Also, C is not Pascal. The equality comparison operator - and the condition - you're looking for is

while (choice == 'Y')

the single equation mark denotes an assignment.

I think you need to use == operator for the comparison in while condition check as:

   while(choice=='Y');

Currently you are using = operator, which is assigning Y to choice variable.

It has been a long time since I programmed in that language, but at a glance, you have:

while(choice='Y');

instead of:

while(choice=='Y');

== compares, = sets equal to. So the while loop is actually not checking the condition you're trying to set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM