文档介绍:Introduction puter(C Programming)
Chapter4 Managing Input and Output operations
introduction
字符输入函数:getchar()
字符输出函数:putchar()
格式输入函数:scanf()
格式输出函数:printf()
C语言本身不提供输入输出语句,输入和输出操作是由函数来实现的。
在C的标准函数库中提供了一些输入输出函数。
例如:printf函数、scanf函数.()中。
printf和scanf不是C语言的关键字。
Reading a character
Reading a single character can be done by using the function getchar.
variable_name = getchar();
Examples:
char name;
name = getchar ();
Example 4_1
The program shows the use of getchar function in an interactive environment.
#include <>
main()
{
char answer;
printf(“Would you like to know my name?\n”)
printf(“Type Y for Yes and N for No:”);
answer = getchar();
if(answer == ‘Y’|| answer == ‘y’)
printf(“\n\nMy name is BUSE BEE\n”);
else
printf(“\n\nYou are good for nothing\n”);
}
Output
Would you like to know my name?
Type Y for YES and N for NO: Y
My name is BUSY BEE
Would you like to know my name?
Type Y for YES and N for NO:n
You are good for nothing
Warning
The getchar() function accepts any character keyed in. This includes RETURN and TAB. This means when we enter single character input, the newline character is waiting in the input queue after getchar() returns. This could create problems when we use getchar() in a loop interactively. A dummy getchar() may be used to ‘eat’ the unwanted newline character. We can also use the fflush function to flush out the unwanted characters.
Note: We shall be using decision statements like if, if……else and while extensively in this chapter. They are discussed in detail in Chapters 5 and 6.
Example 4_2
The program requests the user to enter a character and displays a message on the screen telling the user whether the character is an alphabet or digit, or any other special character.
#include <>
#include <>
main()
{
char character;
printf(“Press any key\n”)
character = getchar();
if(isalpha(character) > 0)
printf(“The character is a letter.”);
else
if(isdigit(character)