0

我正在做一个班级作业(未评分),但不清楚为什么这段代码会导致我的程序“挂起”而不是通过循环运行。

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

2 回答 2

1

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

注意:如果您使用dowhile 循环,为什么在循环之前要求输入?即使输入良好,您的程序也会进入循环。即使没有doasnbStars初始化为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");
}
于 2012-09-03T18:19:27.463 回答
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 );
}
于 2012-09-06T17:34:50.427 回答