Input Validation Patterns
Parse Integer Status
Parsing code should return an explicit status instead of assuming text is valid.
Parse Integer Status
parse_int_status.c
#include <stdio.h>
#include <stdlib.h>
int parseInt(const char *text, int *outValue) {
char *end = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return 0;
}
if (value < -100 || value > 100) {
return 0;
}
*outValue = (int)value;
return 1;
}
int main(void) {
int inputCase = ;
const char *text = "42";
if (inputCase == 1) {
text = "17x";
} else if (inputCase == 2) {
text = "150";
}
int value = 0;
int ok = parseInt(text, &value);
printf("inputCase=%d ok=%d value=%d\n", inputCase, ok, value);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int parseInt(const char *text, int *outValue) {
char *end = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return 0;
}
if (value < -100 || value > 100) {
return 0;
}
*outValue = (int)value;
return 1;
}
int main(void) {
int inputCase = ;
const char *text = "42";
if (inputCase == 1) {
text = "17x";
} else if (inputCase == 2) {
text = "150";
}
int value = 0;
int ok = parseInt(text, &value);
printf("inputCase=%d ok=%d value=%d\n", inputCase, ok, value);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int parseInt(const char *text, int *outValue) {
char *end = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return 0;
}
if (value < -100 || value > 100) {
return 0;
}
*outValue = (int)value;
return 1;
}
int main(void) {
int inputCase = ;
const char *text = "42";
if (inputCase == 1) {
text = "17x";
} else if (inputCase == 2) {
text = "150";
}
int value = 0;
int ok = parseInt(text, &value);
printf("inputCase=%d ok=%d value=%d\n", inputCase, ok, value);
return 0;
}
parse status
`strtol` can report where parsing stopped so the program can reject partial input.
range limit
A valid number can still be outside the range accepted by the program.