【问题标题】:Check user input in C with scanf()使用 scanf() 检查 C 中的用户输入
【发布时间】:2023-03-18 14:54:01
【问题描述】:

目的:

如果用户输入bfloat 数字,则打印floor(b), round(b), ceil(b)

其他打印scanf error: (%d)\n

指令(由我们的老师提供)有这样的代码,我不明白。

这是我的代码: `

#include <stdio.h>
#include <math.h>

int main(void) {
    float b;
    printf("Eneter a float number");
    int a=0;
    a=5;
    a=scanf("%d", &b);
    if (a=0)
    {
        printf("scanf error: (%d)\n",a);
    }
    else
    {
        printf("%g %g %g",floor(b), round(b), ceil(b));
    }
    return 0
}

【问题讨论】:

  • 也许阅读这篇文章可能会有所帮助 - man scanf
  • 你不能使用 "%d" 作为浮点数。
  • @EdHeal:也使用-Wall(或等效项,取决于编译器)进行编译。 GCC -Wall 会发现 a=0%d 错误。
  • "指令(我们老师提供的)有这样的代码,我看不懂。" --> 问老师。否则你没有“老师”。
  • 另外,请修正Enter的拼写

标签: c if-statement input


【解决方案1】:

错误 #1

if (a=0)  // condition will be always FALSE

必须

if (a==0)

或更好

if (0 == a)

错误 #2

scanf("%d", &b); // when b is float

而不是

scanf("%f", &b);

更新:

实际上,对于scanf 的检查结果,我个人更喜欢将!= 与最后一个scanf 输入的值一起使用。例如。如果两个逗号分隔的整数需要继续计算,sn-p 可以是:

int x, y;
int check;
do{
    printf("Enter x,y:");
    check = scanf("%d,%d", &x, &y); // enter format is x,y
    while(getchar()!='\n'); // clean the input buffer
}while(check != 2);

如果check 不是2,即如果它是0(即使第一个值不正确,例如abc,12)或者它是1(当用户忘记逗号或在逗号后输入非数字时,例如12,y

【讨论】:

  • Yoda 并不好(现代编译器可以解决这个问题)
  • @EdHeal 你已经证明他的老师在标准的基础上是愚蠢的,但他不是因为他使用编译器而不只是阅读这些标准。
  • 为什么0 == aa==0 好?
  • 0 == aa==0 好,因为编译器在编译时发现错误0=a,但是当你在a==0 出错时认为a=0 是正确的
【解决方案2】:

带有更正和 cmets 的代码 - 也可在此处获得 - http://ideone.com/eqzRQe

#include <stdio.h>
#include <math.h>

int main(void) {
    float b;
//    printf("Eneter a float number");
    printf("Enter a float number"); // Corrected typo
    fflush(stdout); // Send the buffer to the console so the user can see it
    int a=0;
//    a=5; -- Not required
    a=scanf("%f", &b); // See the manual page for reading floats
    if (a==0) // Need comparison operator not assignemnt
    {
        printf("scanf error: (%d)\n",a); // A better error message could be placed here
    }
    else
    {
        printf("%g\n", b); // Just to check the input with ideone - debugging
        printf("%g %g %g",floor(b), round(b), ceil(b));
    }
    return 0; // You need the semi-colon here
}

为了 VenuKant Sahu 的好处

返回值

这些函数返回成功匹配的输入项数 和分配,它可以比规定的要少,甚至为零 早期匹配失败的事件。

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

【讨论】:

  • 请告诉我我是否正确。 scanf("%f", &amp;b)是一个函数,运行后返回1或0,1表示运行,0表示不运行。那么我可以将其视为布尔值吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-09
  • 1970-01-01
相关资源
最近更新 更多