2012-09-03 63 views
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); 
} 
+0

它在哪里挂?在getchar也许? – BlackBear

+0

首先将\ n添加到显示的消息的末尾。另外:不要重复自己;您也可以将第一个scanf放入循环中(:=仅使用一个scanf()) – wildplasser

+0

它以什么方式“挂起”?有什么症状? –

回答

1

一定有别的事情上,因为你的代码工作在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); 
} 
1

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

注意:如果您在使用do while循环时,为什么在循环之前要求输入?即使输入良好,您的程序也会进入循环。即使没有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"); 
} 
+0

很奇怪。我仍然只是黑屏。 –