To include the header file in your project, run:
wget https://raw.githubusercontent.com/csknk/input-integer-C/master/include/integer-input.h
View the file before downloading
Learning notes and exercises on integer input in C.
At first glance, scanf()
looks like a reasonable way to collect integer input. The function allows formatted input to be collected (it's name comes from the words "scan formatted").
To scan integer input, first declare an integer and pass a pointer to this to scanf:
int input;
scanf("%d", &input);
However, because stdin is inherently unconstrained (users can type anything), scanf()
may not be the best choice. You need to handle whitespace characters appropriately as well as clearing the input stream for subsequent input because scanf()
doesn't read newlines.
Note that fscanf()
which scans a FILE
stream and sscanf()
which scans a string are rational and useful choices because they operate on structured data.
It may be better to read the whole line using fgets()
, and then process the input as required:
- Use
fgets()
to read an entire line of stdin within a while loop. - Check the length of the input buffer - even though
fgets()
discards extra input, the user should be informed if input has exceeded available space and allowed to re-enter the data. - Convert input to an integer using
strtol()
. - If input meets the length constraint and can be interpreted as an integer, the loop ends.
See integer-input.h in this repo.
Example for integer input in C++:
#include <iostream>
#include <typeinfo>
#include <limits>
int main()
{
int input = 0;
while (1) {
std::cout << "Enter an int:\n";
// Enter this block if taking input from cin has failed.
if (!(std::cin >> input)) {
// The error flag is set on std::cin - future attempts to
// get input will fail unless the error is cleared.
std::cin.clear();
// The failed input is in the input buffer. The default for `ignore` is
// to skip a single character. To be sure, remove the max streamsize
// number of chars up until a newline is encountered
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
continue;
}
break;
}
std::cout << "You entered: " << input << '\n';
return 0;
}
- scanf() leaves newline in buffer
- Concise description of
fgets()
vsscanf()
(TLDR; usefgets()
) - comp.lang.c list -
scanf()
problems re: stdin scanf()
and whitespace- Clean & compact description of
fgets()
andstrtol()