简体   繁体   中英

While loop causes program to hang

I am working on a class assignment (non-graded) and am unclear as to why this piece of code results in my program "hanging" vs running through the loop.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int nbStars = 0;        // User defines the number of stars to display
    int nbLines = 0;        // User defines the number of lines on which to print

    // Obtain the number of Stars to display
    printf("Enter the number of Stars to display (1-3): ");
    scanf("%d", &nbStars);
    getchar();

    //   Limit the values entered to between 1 and 3
    do {
        printf("Enter the number of Stars to display (1-3): ");
        scanf("%d", &nbStars);

        if (nbStars < 1 || nbStars > 3) puts("\tENTRY ERROR:  Please limit responses to between 1 and 3.\n");
    } while (nbStars < 1 || nbStars > 3);
}

Output is usually line buffered, if you don't print a new line ( "\\n" ), you won't see any output. Your program is not hanged, it's just waiting for input.

Note: if you're using do while loops, why do you ask for input before the loop? Your program will enter the loop even with good input. And it would work even without do as nbStars is initialized to 0 .

while (nbStars < 1 || nbStars > 3) {
    printf("Enter the number of Stars to display (1-3): \n");
    scanf("%d", &nbStars);

    if (nbStars < 1 || nbStars > 3) puts("\tENTRY ERROR:  Please limit responses to between 1 and 3.\n");
}

There must be something else going on because your code works on both Linux with GCC and Windows 7 cygwin with GCC. Can you provide more details about the input you are using and your environment?

Try this code to see if you get different behavior:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int nbStars = 0;        // User defines the number of stars to display
    int nbLines = 0;        // User defines the number of lines on which to print

    // Obtain the number of Stars to display
    do
    {
        printf("Enter the number of Stars to display (1-3): ");
        scanf("%d", &nbStars);

        if (nbStars < 1 || nbStars > 3)
        {
            puts("\tENTRY ERROR:  Please limit responses to between 1 and 3.\n");
        }
    }while (nbStars < 1 || nbStars > 3);

    printf("You entered %d\n", nbStars);
    return( 0 );
}

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