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, you need to understand memory addresses, which are covered later. For now, just use scanf as it is described.)
Using scanf
The first parameter of scanf is a format string describing the things to be read. After that is a list of memory addresses of variables where the values that are read should be put. The memory address of variable z is written &z. For example, statement scanf("%i%i", &x, &y);reads two integers and stores them into variables x and y, which must have type int. The first value goes into x and the second one into y. Formats for reading include
|
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. To test for EOF, write EOF, not −1. That way, a reader understands what you are doing. For example, if(status == EOF) { ... } |
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. |
You won't need getchar right away, but you can come
back to this part when you need it. We use a function definition,
not yet covered, to illustrate getchar
Function getchar reads a character from the standard input and returns that character. But if there are no more characters available, it returns EOF. 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. It uses a while-loop, covered later. void echoStdin() { int c; c = getchar(); while(c != EOF) { putchar(c); c = getchar(); } } |
Input source. Follow the assignment concerning where to get input.
Input format. Follow the assignment concerning what the input looks like. Do not make up your own input format.
Write C++ code to create a variable n of type int and then read one integer and store it into n. Answer