2014-09-24 94 views
-1

因此,当系统提示输入p的值时,如果输入的字符太少,它会将我带到下一行而不是下一个提示。如果我输入一个足够大的输入,它工作正常。此外,我重新运行该程序似乎不起作用。C程序跳过一行

#include <stdio.h> 
#include <math.h> 
#include <limits.h> 
#include <ctype.h> 
int main() 
{ 
    char pbuffer[10], qbuffer[10], kbuffer[10]; 
    int p=0, q=0, k=0; 
    int r, i, Q, c, count, sum; 
    char a[3]; 
    a[0]='y'; 

    while(a[0]=='y' || a[0]=='Y') 
    { 
     printf("Enter a p value: \n"); 
     fgets(pbuffer, sizeof(pbuffer), stdin); 
     while ((c = fgetc(stdin)) != '\n' && c != EOF); 
     p = strtol(pbuffer, (char **)NULL, 10); 

     printf("Enter a q value: \n"); 
     fgets(qbuffer, sizeof(qbuffer), stdin); 
     while ((c = fgetc(stdin)) != '\n' && c != EOF); 
     q = strtol(qbuffer, (char **)NULL, 10); 

     printf("Enter a k value: \n"); 
     fgets(kbuffer, sizeof(kbuffer), stdin); 
     while ((c = fgetc(stdin)) != '\n' && c != EOF); 
     k = strtol(kbuffer, (char **)NULL, 10); 

     while(p<q+1) 
     { 
     Q=p; 
     sum=0; 
     count=0; 
     while(Q>0) 
     { 
      count++; 
      r = Q%10; 
      sum = sum + pow(r,k); 
      Q = Q/10; 
     } 

     if (p == sum && i>1 && count==k) 
     { 
      printf("%d\n",p); 

     } 
     p++; 
     a[0]='z'; 
     } 
     while((a[0]!='y') && (a[0]='Y') && (a[0]!='n') && (a[0]!='N')) 
     { 
     printf("Would you like to run again? (y/n) "); 
     fgets(a, sizeof(a), stdin); 
     } 
     while ((c = fgetc(stdin)) != '\n' && c != EOF); 
    } 
    return 0; 
} 

输出:

Enter a p value: 
1 
1 
Enter a q value: 
1000 
0 
+0

您的程序和输出不匹配。这不是你在这个问题中描述的问题,也有比计划更多的输出。 – Wug 2014-09-24 02:49:59

+0

这正是我得到的输出结果。我拍了一张照片,但现在不能和我的小代表一起发表。 – 2014-09-24 03:05:15

+0

然后您的发布代码已过期。您不打印您读取的值,但您的提示之间有2个数字。当我逐字运行此代码时,它会打印出不同的内容。 – Wug 2014-09-24 03:18:20

回答

0

首先,你必须在代码行错误

while((a[0]!='y') && (a[0]='Y') && (a[0]!='n') && (a[0]!='N')) 

你已经错过了 '!'字符在第二个条件 而对于你的问题,什么是使用这一行的原因:

while ((c = fgetc(stdin)) != '\n' && c != EOF); 

如果我们用控制台的工作只是等待一个更“\ n” 因为前一个是采取与fgets