C input error (simple addition program)

I'm trying to make a program in C, that you enter two numbers into (a and b), it then shows "a+b=n" and returns 0, BUT if the user inputs invalid characters, the program shouldnt write a+b=n and should return 1.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>  /* scanf(), printf() */
#include <stdlib.h> /* EXIT_* */
#include <ctype.h>

int main(void)
{
int a, b, n;
    scanf("%d%d", &a,&b);
    if(isdigit(a) && isdigit(b))
    {
        n = a + b;
        printf("%d+%d=%d.\n", a, b, n);
        return 0;
    }
    else
    {
        return 1;
    }
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

int main(){

	int a, b;

	if (std::cin >> a >> b)
		std::cout << a + b << std::endl;
	else{
		std::cerr << "Input Wrong.\n";
                return 1;
         }

	return 0;
}
Last edited on
The isdigit function is intended for characters, not integers.

scanf returns the number of values that was successfully read. You are reading two integer values so you want scanf to return 2.

1
2
3
4
5
6
7
8
if(scanf("%d%d", &a,&b) == 2)
{
	// success
}
else
{
	// failure
}
Topic archived. No new replies allowed.