Hardware Reference
In-Depth Information
character can be returned from the keyboard:
/* Name:
getin1.c
*/
/* Language: Borland C++ 4.5
*/
/* Output:
Table of decimal, hex. and ASCII characters */
/* Note:
Program runs in a DOS console window
*/
#include <stdio.h>
int main()
{
char c;
c = inchar("Enter option required... ");
printf("\n\nOption selected = %c\n", c);
return 0;
}
int inchar(prompt)
char *prompt;
{
printf("\n%s",prompt);
return(getchar());
}
Here we have defined a function, inchar , which returns an integer to main.
This is automatically converted to a character and assigned to the variable, c .It
is important to note that the return key is used to terminate user input and, where
the user provides more than one input character before pressing the return key,
only the first character is returned by getchar() .
Where a multiple (rather than single) character string is required, the scanf()
function can be used, as shown in the following code fragment:
int getcode()
{
char code[16];
printf("Enter operator code... ");
scanf("%s", code);
}
The following Borland C ++ 4.5 program shows how a string of characters can
be accepted from the user and then printed on the screen:
/* Name:
getin2.c
*/
/* Language: Borland C++ 4.5
*/
/* Output:
Table of decimal, hex. and ASCII characters */
/* Note:
Program runs in a DOS console window
*/
#include <stdio.h>
int main()
{
char code[16];
printf("Enter operator code... ");
scanf("%s", code);
printf("\nCode entered: %s", code);
return 0;
}
The scanf() function allows a similar set of conversion characters to that
available for use within printf() . It is important to note that scanf() ter-
minates input when a return, space or tab character is detected. Furthermore,
the array must be sufficiently large to accommodate the longest string likely to
Search WWH ::




Custom Search