|
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)
{
...
}
|
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.
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
|