LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   do while loop problem (https://www.linuxquestions.org/questions/programming-9/do-while-loop-problem-4175548044/)

NoWeDoR 07-15-2015 07:18 AM

do while loop problem
 
Code:

#include <stdio.h>

int main()
{
        int choice;
        do
        {
                printf("Enter your choice: ");
                scanf("%d", &choice);
                switch (choice)
                {
                case 1:
                {
                        printf("Hello World\n\n");
                        break;

                }
                case 2:
                {
                        printf("Hello World2\n\n");
                        break;
                }
                case 3:
                {
                        printf("Hello World3\n\n");
                        break;
                }
                default:
                {
                        return 0;
                        break;
                }
                }
        } while (choice >= 1 && choice <= 3);
        return 0;
}

1) Like a this program, at first, when you enter unmeaning values (like * - / + . , etc.) as choice it is stopping as it should be.
2) However, at first when you enter as choice 1,2 or 3 and then enter unmeaning values (like * - / + . , etc.) it is starting to loop forever.

Although at first isn't a thing like this, Why is it happening at second?

NevemTeve 07-15-2015 07:29 AM

Forget scanf, use fgets and sscanf. Don't ignore the return values.

rhubarbdog 07-28-2015 03:29 PM

First lap the entered data matches d so is sucessfully matched to choice. Second lap the scanf matches no data. This time %d doesn't effect choice, but the previous value is still available to switch statement

Try choice=0; before scanf or more precisely catch the value returned by scanf and act accordingly. In this case anything other than 1 implies some sort of error.


All times are GMT -5. The time now is 12:31 AM.