Hardware Reference
In-Depth Information
be input. Since the string is automatically terminated by a null character, the
array must be dimensioned so that its number of elements is one greater than
the maximum string length.
Multiple arguments may be included within
scanf()
. It is important to note
that, unlike
printf()
, the arguments to
scanf()
are pointers (not variables
themselves). This point regularly causes confusion. Finally, since
scanf()
involves considerable overhead, simpler functions may be preferred where the
space for code is strictly limited.
The following example illustrates the combined use of
getchar()
,
printf()
, and
scanf()
in a simple decimal to hexadecimal conversion utility:
/* Name:
hexdec.c
*/
/* Language: Borland C++ 4.5
*/
/* Output:
Hexadecimal equivalent of decimal input
*/
/* Note:
Program runs in a DOS console window
*/
#include <stdio.h>
#include <stdlib.h>
int main()
{
char number[16];
int num, c;
num=1;
printf("DECIMAL TO HEXADECIMAL CONVERSION\n");
printf("=================================");
while(num != 0)
{
printf("\n\nEnter decimal number (max. 65535) or 0 to
quit: ");
scanf("%s", number);
num = atoi(number);
printf("Decimal %u = %X hexadecimal", num, num);
}
return 0;
}
The expression following while evaluates true if the current value of
num
is
non-zero. In such cases, the code following while is executed and the ASCII
character string is converted to an integer by means of the
atoi()
function. If
the user responds with 0 (or with a non-numeric character string) and expres-
sion evaluates false, the code following while is not executed and the program
terminates. The output produced by the program is shown in Figure 7.8.
Menu selection
It is often necessary to provide users with a choice of several options at some
point in a control program. Fortunately, C offers the switch case statement which
is ready made for this particular purpose. Complex menu selections can be very
easily implemented using the
switch case
logical construct. The following
example shows how:
/* Name:
menu1.c
*/
/* Language: Borland C++ 4.5
*/
/* Output:
Menu routine
*/
/* Note:
Program runs in a DOS console window
*/