#include <stdio.h>
int main() {
int a, b, c;
printf("Enter three integers: ");
scanf("%d %d %d", &a, &b, &c);
printf("You entered: %d, %d, %d\n", a, b, c);
return 0;
}
#include <stdio.h>
int main() {
int number;
int result = scanf("%d", &number);
if (result == 1) {
printf("Valid integer input: %d\n", number);
} else {
printf("Invalid input\n");
}
return 0;
}
#include <stdio.h>
#include <limits.h>
int main() {
int number;
printf("Enter an integer between %d and %d: ", INT_MIN, INT_MAX);
while (scanf("%d", &number) != 1) {
printf("Invalid input. Try again: ");
while (getchar() != '\n'); // Clear input buffer
}
printf("Valid input: %d\n", number);
return 0;
}
Technique |
Pros |
Cons |
Basic scanf() |
Simple, direct |
No built-in validation |
Validated scanf() |
Input checking |
Requires extra code |
Buffer Clearing |
Prevents input errors |
More complex |
graph TD
A[Start Input] --> B{Input Method}
B -->|Simple| C[Direct scanf()]
B -->|Advanced| D[Validated scanf()]
C --> E[Store Value]
D --> F{Input Valid?}
F -->|Yes| E
F -->|No| G[Retry Input]
Best Practices
- Always validate integer inputs
- Use buffer clearing for robust input
- Check return values of scanf()
LabEx recommends mastering these techniques for reliable integer input handling.