输入两个数字的值

Bal*_*ran 0 c input scanf

实际上,我正在学习C语言,并且编写了一个程序

输入2个数字的值,如下所示。

#include<stdio.h>
int main()
{
    int a, b, c;
    printf("Enter two numbers to add\n");
    scanf("%d%d", &a, &b);
    printf("Sum of the numbers = %d\n", c);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我输入一个字母,我会得到一些1522222数字。取而代之的是,如果我输入字母(即a,b,c),它会抛出错误作为无效输入。

我该怎么办?

Bla*_*aze 6

您可以检查的返回值scanf。如果成功,它将返回2,因为您正在读取两个值。如果还有其他问题,则说明输入不正确。尝试这个:

if (scanf("%d%d", &a, &b) != 2)
    printf("Invalid input type!\n");
else 
    printf("Sum of the numbers = %d\n", a+b);
Run Code Online (Sandbox Code Playgroud)

另一方面,您无需c在任何地方初始化,因此打印它是未定义的行为。您甚至不需要这样做c,只需打印即可a+b

  • @SaurabhPBhandari:不,那太荒谬了。这是一个很好的答案。 (2认同)