其实我在学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;
}
但是如果我输入一个字母表,我会得到一些 1522222 个数字。代替 我希望它在我键入字母表即 a、b、c 时抛出错误作为无效输入。
我该怎么做?
最佳答案
可以查看scanf
的返回值.如果成功,它应该返回 2
,因为您正在读取两个值。如果你得到任何其他东西,你就知道输入不正确。试试这个:
if (scanf("%d%d", &a, &b) != 2)
printf("Invalid input type!\n");
else
printf("Sum of the numbers = %d\n", a+b);
换句话说,您没有在任何地方初始化 c
,因此打印它是未定义的行为。你甚至不需要 c
,你可以打印 a+b
来代替。
关于c - 输入两个数字的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56537986/