0

Actually, I'm learning C langage and I have written a programm

Enter the value of 2 numbers as shown below.

#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;
}

But if I enter an alphabet I'm getting some 1522222 numbers. Instead of this I want it throws an error as invalid input if I type alphabet ie a,b,c.

How could I do that?

Blaze
  • 16,736
  • 2
  • 25
  • 44
  • Please do some research of your own before asking on SO. A simple google search will help, e.g.: https://study.com/academy/lesson/validating-input-data-in-c-programming.html – Adrenaxus Jun 11 '19 at 06:57
  • 2
    You never add `a` and `b` so what do you expect. You are kind of asking "what's the result of `1 + 1` if we never add the operands together". Very very basic elementary school math. – Lundin Jun 11 '19 at 06:58

1 Answers1

6

You can check the return value of scanf. If it is successful, it should return 2, since you're reading two values. If you get anything else, you know that the input is incorrect. Try this:

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

On a different note, you don't initialize c anywhere, so printing it is undefined behavior. You don't even need c for this, you can just print a+b instead.

Blaze
  • 16,736
  • 2
  • 25
  • 44