Show contents
Chapter 2 of 6 · 20 min
Input and errors under control
By the end of this chapter, you'll be able to
- Convert text to a number safely with strtol, errno and endptr
- Read input line by line with fgets rather than with scanf
- Design functions that return an error code and a result
- Release every resource on every error path with a single exit point
Converting without getting caught out: strtol
atoi("12abc") returns 12 and atoi("abc") returns 0, with no way of knowing the input was invalid. strtol, from <stdlib.h>, says much more: it returns the value, tells you where it stopped reading, and sets errno to ERANGE if the number is too big.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
/* Converts text to an int. Returns 0 if all is well, -1 otherwise. */
int read_int(const char *text, int *result) {
char *end;
errno = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0') {
return -1; /* not a number, or extra characters */
}
if (errno == ERANGE || value < INT_MIN || value > INT_MAX) {
return -1; /* too big for an int */
}
*result = (int)value;
return 0;
}
int main(void) {
const char *tries[] = {"42", "-7", "12abc", "", "99999999999"};
for (size_t i = 0; i < sizeof tries / sizeof tries[0]; i++) {
int n;
if (read_int(tries[i], &n) == 0) {
printf("\"%s\" -> %d\n", tries[i], n);
} else {
printf("\"%s\" -> refused\n", tries[i]);
}
}
return 0;
}
"42" -> 42
"-7" -> -7
"12abc" -> refused
"" -> refused
"99999999999" -> refused
endreceives the address of the first character not read. If it hasn't moved (end == text), no digit was read; if it doesn't point to'\0', there are characters left over.- We reset
errnoto 0 before the call:strtolnever resets it itself. - The function follows a very common C pattern: it returns an error code (0 or -1) and gives its result through a pointer (
int *result).
Reading input: fgets, then conversion
scanf("%d", &age) leaves in the keyboard buffer everything it couldn't read, which makes the next read fail. The robust method: read the whole line with fgets, then convert it.
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_int(const char *text, int *result) {
char *end;
errno = 0;
long value = strtol(text, &end, 10);
if (end == text || *end != '\0' || errno == ERANGE || value < INT_MIN || value > INT_MAX) {
return -1;
}
*result = (int)value;
return 0;
}
int main(void) {
char line[32];
int age;
while (fgets(line, sizeof line, stdin) != NULL) {
line[strcspn(line, "\n")] = '\0';
if (read_int(line, &age) == 0 && age >= 0 && age < 150) {
printf("%s -> in 10 years: %d\n", line, age + 10);
} else {
printf("%s -> invalid input\n", line);
}
}
return 0;
}
17
seventeen
200
17 -> in 10 years: 27
seventeen -> invalid input
200 -> invalid input
strcspn(line, "\n") gives the position of the first '\n' (or the string's length if there isn't one): we replace it with '\0' to remove the line break.
A single exit point to release everything
When a function opens several resources (files, memory), each failure must release what has already been obtained. Repeating the clean-up at each return is a classic source of omissions. In C, the recognised pattern uses goto to a single exit label:
#include <stdio.h>
#include <stdlib.h>
/* Copies the non-empty lines from source to destination. Returns the number of lines, or -1. */
int copy_non_empty(const char *source, const char *destination) {
int result = -1;
int copied = 0;
char *buffer = NULL;
FILE *out = NULL;
FILE *in = fopen(source, "r");
if (in == NULL) goto end;
out = fopen(destination, "w");
if (out == NULL) goto end;
buffer = malloc(256);
if (buffer == NULL) goto end;
while (fgets(buffer, 256, in) != NULL) {
if (buffer[0] != '\n') {
fputs(buffer, out);
copied++;
}
}
result = copied;
end:
free(buffer);
if (out != NULL) fclose(out);
if (in != NULL) fclose(in);
return result;
}
int main(void) {
FILE *f = fopen("draft.txt", "w");
if (f == NULL) return 1;
fputs("line 1\n\nline 2\n\n\nline 3\n", f);
fclose(f);
printf("copied: %d\n", copy_non_empty("draft.txt", "clean.txt"));
printf("missing source: %d\n", copy_non_empty("missing.txt", "x.txt"));
remove("draft.txt");
remove("clean.txt");
return 0;
}
copied: 3
missing source: -1
All the resources are initialised to NULL at the start; the end: label only releases what was obtained (free(NULL) does nothing, by definition). Wherever the failure happens, there's only one exit path to check.
Normal path: everything succeeds, the work is done, then we also go through end to release everything.
Text description of the animation
- First path: the source doesn't exist. goto end, nothing else was obtained.
- The label only releases what isn't NULL: here, nothing.
- Second path: the source opens…
- …but not the destination. goto end.
- The label closes the source, already open. No leak.
- Normal path: everything succeeds, the work is done, then we also go through end to release everything.
Your turn
Worked exercise
Worked exercise: converting a price to cents
Write a function int read_price(const char *text, long *cents) that accepts a price in the format 12 or 12.5 or 12.50 (at most two digits after the point) and gives the amount in cents (1250). It returns -1 for any invalid input: 12.505, abc, -3, 12,50 or an empty string. Use strtol, no floating-point numbers: a price stored as a double accumulates rounding errors.
Hint 1
strtol(text, &end, 10). If *end == '.', then read the digits that follow, one by one, with a loop.Hint 2
*p >= '0' && *p <= '9' tests whether a character is a digit, and *p - '0' gives its value. A single digit after the point counts as tens of cents.Show the solution and common mistakes
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int read_price(const char *text, long *cents) {
char *end;
errno = 0;
long units = strtol(text, &end, 10);
if (end == text || errno == ERANGE || units < 0 || text[0] == '-') {
return -1;
}
long fraction = 0;
if (*end == '.') {
const char *p = end + 1;
int digits = 0;
while (*p >= '0' && *p <= '9') {
if (++digits > 2) return -1;
fraction = fraction * 10 + (*p - '0');
p++;
}
if (digits == 0) return -1;
if (digits == 1) fraction *= 10;
end = (char *)p;
}
if (*end != '\0') return -1;
*cents = units * 100 + fraction;
return 0;
}
int main(void) {
const char *tries[] = {"12", "12.5", "12.50", "0.07", "12.505", "abc", "-3", "12,50", ""};
for (size_t i = 0; i < sizeof tries / sizeof tries[0]; i++) {
long c;
if (read_price(tries[i], &c) == 0) {
printf("%-7s -> %ld cents\n", tries[i], c);
} else {
printf("%-7s -> refused\n", tries[i]);
}
}
return 0;
}
12 -> 1200 cents
12.5 -> 1250 cents
12.50 -> 1250 cents
0.07 -> 7 cents
12.505 -> refused
abc -> refused
-3 -> refused
12,50 -> refused
-> refused
By counting in whole cents, you avoid floating-point rounding errors: 0.1 + 0.2 isn't exactly 0.3 as a double. That's the rule for any amount of money.
Common mistakes:
- Using
atoforstrtodthen multiplying by 100:0.29 * 100gives28.999999999999996, and converting tolongtruncates to 28 cents. - Forgetting to check
*end != '\0'at the end:12,50would be accepted as12.
Summary
- 1In C, each function reports failure through its return value: look at it on every call.
- 2strtol with endptr and errno converts text while refusing invalid or oversized input.
- 3Read input line by line with fgets, then convert it: it's safer than scanf.
- 4A function often returns an error code and gives its result through a pointer.
- 5A single exit point (goto end) releases every resource on every error path.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.