While Loop skipping scanf for it's condition.

我是研究僧i 提交于 2019-12-13 01:18:04

问题


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;

}


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/14009353/while-loop-skipping-scanf-for-its-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!