BETA Try the new lesson view
Code

Your own input module

Now your own input module, from the pieces in step 4. It has two functions: one reads a line, the other turns text into a number. The program p09_numbers uses them to add up a sum.

CMakeLists.txt – a library and a program, as in topic 7:

add_library(p09_safe_input STATIC safe_input.c)
target_include_directories(p09_safe_input PUBLIC .)

add_executable(p09_numbers numbers.c)
target_link_libraries(p09_numbers PRIVATE p09_safe_input)

course_input isn't used here: all the input is yours.

safe_input.h – two functions with Doxygen contracts:

  • int get_line(char t[], int size) returns three cases: 1 – the line fit, 0 – too long, -1 – the input ended. What to do about each is up to the caller.
  • int to_int(const char *t, int *result) returns 1 or 0, and gives the number back through a pointer. That way "doesn't fit" is never confused with the number 0.

safe_input.c:

  • static int echo_input(void) is the INPUT_ECHO check. static: only this file needs it (topic 7).
  • get_line does step 4's three jobs after fgets: NULL → -1; no '\n' and not the end of the file → the rest is thrown away with getchar, returns 0; otherwise it's cut with strcspn. The echo shows even a too-long line whole, as you'd see it in the console.
  • to_int is strtol plus four checks: were there digits, are there only spaces at the end, not ERANGE, does it fit in an int.

numbers.c is a loop: the prompt > with fflush, a line, q to end (strcmp), otherwise to_int and the sum.

Run it

p09_numbers and ▶. Type one at a time: 42, -7, 12abc, abc, 99999999999, a long row of digits, 8 (with a space in front) and q:

Whole numbers one per line, q to stop.
> 42
OK: 42, sum 42
> -7
OK: -7, sum 35
> 12abc
"12abc" is not a whole number.
> abc
"abc" is not a whole number.
> 99999999999
"99999999999" is not a whole number.
> 123456789012345678901234
Line too long: at most 18 characters.
>  8
OK: 8, sum 43
> q
Sum: 43

t has 20 bytes: 18 characters, '\n' and '\0'.

Without fflush

Delete fflush(stdout); and run it again. In CLion the > may show up only after you've already typed the number. Put the line back (Ctrl+Z).

Commit: Add safe_input module.