If you really want to deal with user input that could be hostile use a separate function for getting the number.
Allows
- leading spaces : " 123"
- trailing spaces : "123 "
- leading zeros : "0000000000000000000000000000000000123"
- Rescans nicely after error input.
Catches the following errors
- No input : ""
- Extra text after the number: "123 abc"
- Text before the number : "abc 123"
- Split number : "123 456"
- Overflow/underflow : "12345678901234567890"
- other : "--123"
Re-prompts on invalid input.
#include <errno.h>
#include <stdio.h>
#include <stddef.h>
int GetInteger(const char *prompt, int *i) {
int Invalid = 0;
int EndIndex;
char buffer[100];
do {
if (Invalid)
fputs("Invalid input, try again.\n", stdout);
Invalid = 1;
fputs(prompt, stdout);
if (NULL == fgets(buffer, sizeof(buffer), stdin))
return 1;
errno = 0;
} while ((1 != sscanf(buffer, "%d %n", i, &EndIndex)) || buffer[EndIndex] || errno);
return 0;
}
int main() {
int a, b, c;
if (GetInteger("Enter first number to add\n", &a)) {
; // End of file or I/O error (rare)
}
if (GetInteger("Enter second number to add\n", &b)) {
; // End of file or I/O error (rare)
}
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
BTW, You should not do printf("Enter first number to add\n")
. Use fputs()
instead. Consider what would happen if the string had a %
in it.