while循环导致程序挂起

时间:2012-09-03 18:12:05

标签: c infinite-loop do-while

我正在进行课程作业(非评分)并且不清楚为什么这段代码导致我的程序“挂起”而不是在循环中运行。

#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);
}

2 个答案:

答案 0 :(得分:1)

输出通常是行缓冲的,如果不打印新行("\n"),则不会看到任何输出。你的程序没有被挂起,它只是在等待输入。

注意:如果你在循环中使用do,为什么在循环之前要求输入?即使输入良好,您的程序也会进入循环。即使没有do,它也会有效,因为nbStars已初始化为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");
}

答案 1 :(得分:1)

必须有其他事情发生,因为你的代码适用于带有GCC的Linux和带有GCC的Windows 7 cygwin。您能否提供有关您正在使用的输入和环境的更多详细信息?

尝试使用此代码查看是否有不同的行为:

#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 );
}