You cannot convert a string to a cast number, for example num1 = num1input; . You need to call the library function from <stdlib.h> :
#include <stdlib.h> ... num1 = atoi(num1input);
But atoi ignores parsing errors. To verify that an overflow has been detected, you can use strtol() as follows:
#include <errno.h> #include <limits.h> #include <stdlib.h> ... errno = 0; char *endp; long lval = strtol(num1input, &endp, 10); if (endp == num1input || errno != 0 || lval < INT_MIN || lval > INT_MAX) { /* parse error detected: * you could print an error message. */ if (lval < INT_MIN) lval = INT_MIN; /* clamp lval as an int value. */ if (lval > INT_MAX) lval = INT_MAX; } num1 = lval;
Or if you want to learn hexadecimal syntax like 0x10 :
num1 = strtol(num1input, NULL, 0);
The same applies for num2input .
Note that isdigit(num1input[i]) potentially incorrect if char signed and num1input[i] has a negative value. You must write:
isdigit((unsigned char)num1input[i])
Also note that float division = num1 / num2; computes integer division and converts the result to float . If you want floating point division, you should write:
float division = (float)num1 / num2;
Note that for best accuracy, it is recommended to use double instead of float .
Here is the adjusted and simplified version:
#include <errno.h> #include <limits.h> #include <stdlib.h> #include <stdio.h> /* simple implementation of strtoi(), inspired by elegant code from chux */ int strtoi(const char *s, char **endptr, int base) { long y = strtol(s, endptr, base); #if INT_MAX != LONG_MAX if (y > INT_MAX) { errno = ERANGE; return INT_MAX; } #endif #if INT_MIN != LONG_MIN if (y < INT_MIN) { errno = ERANGE; return INT_MIN; } #endif return (int)y; } int main(void) { char num1input[20]; char num2input[20]; char *endp; int num1, num2; for (;;) { printf("Please enter a number: "); if (scanf("%19s", num1input) != 1) return 1; errno = 0; num1 = strtoi(num1input, &endp, 10); if (errno == 0 && *endp == '\0') break; printf("Input is not a number\n"); } for (;;) { printf("Please enter a second number: "); if (scanf("%19s", num2input) != 1) return 1; errno = 0; num2 = strtoi(num2input, &endp, 10); if (errno == 0 && *endp == '\0') break; printf("Input is not a number\n"); } printf("%d %d\n", num1, num2); int addition = num1 + num2; int subtraction = num1 - num2; int multiplication = num1 * num2; double division = (double)num1 / num2; printf("Addition: %d Subtraction: %d Multiplication: %d Division: %g\n", addition, subtraction, multiplication, division); getch(); }