graph TD
A[User Input] --> B{Validate Input}
B -->|Valid| C[Process Input]
B -->|Invalid| D[Error Handling]
C --> E[Store/Transform Data]
D --> F[Request Retry]
#define MAX_INPUT 100
char buffer[MAX_INPUT];
if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
// Remove trailing newline
buffer[strcspn(buffer, "\n")] = 0;
// Process input
printf("You entered: %s\n", buffer);
}
int parse_integer(const char *input) {
char *endptr;
long value = strtol(input, &endptr, 10);
// Check for conversion errors
if (endptr == input) {
fprintf(stderr, "No valid number found\n");
return -1;
}
// Check for overflow
if (value > INT_MAX || value < INT_MIN) {
fprintf(stderr, "Number out of range\n");
return -1;
}
return (int)value;
}
Technique |
Use Case |
Pros |
Cons |
fgets() |
Safe string input |
Secure |
Limited flexibility |
getline() |
Dynamic string input |
Flexible |
Overhead |
sscanf() |
Formatted input parsing |
Versatile |
Complex parsing |
strtok() |
Token-based parsing |
Useful for delimited input |
Modifies original string |
typedef struct {
char name[50];
int age;
float salary;
} Employee;
int read_employee_data(Employee *emp) {
printf("Enter name, age, and salary: ");
if (scanf("%49s %d %f",
emp->name,
&emp->age,
&emp->salary) != 3) {
fprintf(stderr, "Invalid input format\n");
return 0;
}
// Additional validation
if (emp->age < 0 || emp->salary < 0) {
fprintf(stderr, "Invalid age or salary\n");
return 0;
}
return 1;
}
Error Handling Strategies
graph TD
A[Input Received] --> B{Validation Check}
B -->|Pass| C[Process Data]
B -->|Fail| D{Error Type}
D -->|Format Error| E[Prompt Retry]
D -->|Range Error| F[Provide Guidance]
E --> A
F --> A
void clear_input_buffer() {
int c;
while ((c = getchar()) != '\n' && c != EOF) {
// Discard remaining characters
}
}
- Minimize memory allocations
- Use stack-based buffers when possible
- Implement efficient parsing algorithms
LabEx Learning Approach
LabEx recommends practicing these techniques through interactive coding exercises to build robust input handling skills.
#define MAX_ATTEMPTS 3
int main() {
char input[100];
int attempts = 0;
while (attempts < MAX_ATTEMPTS) {
printf("Enter a valid number: ");
if (fgets(input, sizeof(input), stdin) == NULL) {
break;
}
int result = parse_integer(input);
if (result != -1) {
printf("Valid input: %d\n", result);
return 0;
}
attempts++;
}
fprintf(stderr, "Maximum attempts reached\n");
return 1;
}
Key Takeaways
- Validate all user inputs
- Implement robust error handling
- Use appropriate input parsing techniques
- Always consider potential input variations