How can I make sure the user inputs numerical values only instead of alphanumeric or any other character? Also what to look for to insert error message for incorrent input?
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter first number to add\n");
scanf("%d",&a);
printf("Enter second number to add\n");
scanf("%d",&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
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.
It's better to avoid using scanf at all. Use fgets to get entire line, and then use sscanf to extract the information you need. Check the return value of sscanf to make sure the input is as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With