2014-02-13 29 views
0

我正在为我的课程之一编写代码,而且我碰到了一堵墙。我需要用户输入一个将被用作for循环重复次数的数字。我要求这个数字的第一个循环是一个while循环。我需要确保输入的值是一个数字,而不是一个字母或特殊字符。如何确保输入的值是一个数字?

我不知道如何确保它不是字母或特殊字符。

下一个问题是确保for循环只运行指定的次数,即第一次循环中提供的次数。

这就是我到目前为止所写的内容。

#include <stdio.h> 

int main() 

{ 

int num_of_scores, n; 
char enter; 
float score=-1, total=0, average; 

do 
{ 
    printf("\n\nEnter the number of quiz scores between 1 and 13: "); 
    scanf ("%d, %c", &num_of_scores, &enter); 
} 
while(num_of_scores<1 || num_of_scores>13/* && enter == '\n'*/); 

printf("\nStill Going!"); 

for(n=0; n<num_of_scores; n++) 
{ 
    printf("\nEnter score %i: ", n+1); 
    scanf ("%f", &score); 
    while(score>=0 || score<=100) 
    { 
     total = total + score; 
     score = -1; 
     break; 
    } 
} 


average = total/num_of_scores; 

printf("\nThe average score is %.0f.\n\n", average); 
return 0; 

}

所以我编辑的代码一点点。在第一个while循环中有一部分位于注释中,因为它在该循环之后使程序结束了。 printf(“仍在继续”)只是一个测试,以确保该程序得到这么多。任何进一步的指针?我仍然不确定如何检查确保没有输入号码。我虽然增加了& & enter =='\ n'会做到这一点,但如果它挂起程序,它是不好的。你提出的很多例子都很好,但是我觉得它们有点混乱。谢谢!

+2

你应该使用它之前初始化值设置为0。 num_of_scores有可能包含垃圾值。 –

+0

约翰我相信我解决了这个问题。我有吗? – jeaboswell

回答

1

检查返回值scanf。每手册页:

返回值

这些函数返回匹配成功并分配输入项目的数量,这可以少于在早期的情况下提供 的,甚至是零匹配失败。

如果在第一次成功转换或发生匹配 故障之前达到输入的结尾,则返回值EOF。如果发生读取错误,则返回EOF,在这种情况下,流的错误指示符(请参阅 ferror(3))已设置,并且设置errno表示错误。

+0

是的,我在课前听说过EOF,但我不确定如何测试。任何提示? – jeaboswell

+0

'int i; i = scanf(...);如果(i == EOF){...}' – abligh

0
do{ 
    char ch = 0; 
    num_of_scores = 0; 
    printf("\nEnter the number of quiz scores between 1 and 13: "); 
    if(scanf("%d%c", &num_of_scores, &ch)!=2 || ch != '\n'){ 
     int ch; 
     while((ch=getchar())!='\n' && ch !=EOF); 
    } 
} while(num_of_scores<1 || num_of_scores>13); 
相关问题