To expand on what jimblumberg and oogabooga said:
If you want your program to complain when the input is not what is expected, you have to check if the input is what you expected. The way your code is written now just assumes the input was as expected.
Code:
#include <stdio.h>
int main(void)
{
int num1;
int num2;
int sum;
printf("Enter the first integer: ");
if (scanf("%d", &num1) != 1) {
printf("That's not an integer.\n");
return 1;
}
printf("Enter second integer: ");
if (scanf("%d", &num2) != 1) {
printf("That's not an integer.\n");
return 1;
}
sum = num1 + num2;
printf("The sum of the two numbers is: %d\n ", sum);
getchar();
return 0;
}
Since scanf() or fscanf() do not consume input they cannot convert, the non-number the user specified stays in the input buffer. You could read it and display it, if you wanted to. Because input is normally line-buffered, it's best to consume the un-scannable input up to (and including) a newline or EOF:
Code:
#include <stdio.h>
int main(void)
{
int num1, num2, sum, c;
printf("Enter the first integer: ");
if (scanf("%d", &num1) != 1) {
c = getchar();
while (c != EOF && c != '\n') {
putchar(c);
c = getchar();
}
printf(": Not an integer.\n");
return 1;
}
printf("Enter second integer: ");
if (scanf("%d", &num2) != 1) {
c = getchar();
while (c != EOF && c != '\n') {
putchar(c);
c = getchar();
}
printf(": Not an integer.\n");
return 1;
}
sum = num1 + num2;
printf("The sum of the two numbers is: %d\n ", sum);
getchar();
return 0;
}