【问题标题】:How to make sure that a value entered is a number? [duplicate]如何确保输入的值是数字? [复制]
【发布时间】:2014-03-12 23:10:31
【问题描述】:

我正在为我的一门课程编写代码,但我碰壁了。我需要用户输入一个数字,该数字将用作重复 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("still going") 只是一个测试,以确保程序能走得那么远。任何进一步的指示?我仍然不确定如何检查以确保未输入数字。我虽然添加 && enter == '\n' 会这样做,但如果它挂起程序那就不好了。您建议的许多示例都很好,但我发现它们有点令人困惑。谢谢!

【问题讨论】:

  • 您应该在使用前将值初始化为 0。 num_of_scores 有可能包含垃圾值。
  • 约翰 我相信我解决了这个问题。我有吗?

标签: c loops math


【解决方案1】:

我会检查 Check if input is integer type in C 以获取此问题的答案...

【讨论】:

  • C 没有try / catch。您可能正在考虑 C++。
  • 您说的完全正确,感谢您指出其中的差异;编辑我的答案以消除混乱。
【解决方案2】:
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);

【讨论】:

    【解决方案3】:

    检查scanf的返回值。根据手册页:

    返回值

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

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

    【讨论】:

    • 是的,我之前在课堂上听说过 EOF,但不确定如何测试它。有什么提示吗?
    • int i; i = scanf ( ... ); if ( i == EOF ) { ... }
    猜你喜欢
    • 1970-01-01
    • 2019-07-23
    • 1970-01-01
    • 2015-05-17
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多