The <cstdio> library also provides a function, scanf, for reading information from stdin. The <cstdio> library is a library for C. C++ programs can use it, but to fully understand what is going on, we need to talk about memory addresses.
Using scanf
What if the read cannot be done?
Sometimes a read cannot be accomplished. For example, if you ask to read an integer, but the program sees abc, then it cannot read the integer. Scanf stops reading at the first failure and returns the number of items successfully read. So
int status = scanf("%i%i", &x, &y);
if(status < 2)
{
what to do if it was not possible to read both x and y
}
is a typical way to use scanf.
If scanf encounters the end of a file without reading any of the items sought, it returns EOF, which is a name for −1. |
Prompts
When a program reads information from the
standard input, it usually writes something to
let the user know to type the required information.
For example,
printf("What number should I use? "); scanf("%i", &num);But do not overdo it. If the input is supposed to have a particular rigid form, don't write a prompt for each line. It is annoying. |
Function getchar.
reads a character from the standard input and returns that character.
But if there are no more characters available, it returns EOF (the same as −1).
Because getchar can return EOF,
which is not a character,
its result has type int, not
char. To illustrate, the following
function reads the entire standard input and writes it verbatim to the standard
output.
void echoStdin() { int c; c = getchar(); while(c != EOF) { putchar(c); c = getchar(); } } |