C programming tutorial (11) - input and output of character data
This column mainly introduces the basic syntax of C language, which is used as the courseware and reference materials of the "Programming Language" course for the teaching of the "Programming Language" course, for entry-level users to read.
Table of contents
In addition to the printff and scanf functions, the standard input and input library functions commonly used in C language also include the getchar function, gets function, putchar function and puts function.
1. getchar function
The function of the getchar function is to input a character from the keyboard. This function has no parameters, and the return value of the function is the input character. The format is as follows:
getchar();
For example:
#include<stdio.h>
int main() {
int x;
char ch;
ch=getchar();
putchar(ch);
return 0;
}
The result of running the above program is as follows:
Two, gets function
The function of the gets function is to receive a character string input from the keyboard and store it in a character array. The return value of the function is the starting address of the character array. The format is as follows:
gets(str);
For example:
#include<stdio.h>
int main() {
char str[10];
gets(str);
printf("%s",str);
return 0;
}
The result of running the above program is as follows:
Three, putchar function
The function of the putchar function is to output a character to the display. Arguments can be characters, escaped characters, or character constants. The format is as follows:
putchar(c);
For example:
#include<stdio.h>
int main() {
int i;
char str[10];
str[0]='G';
str[1]='o';
str[2]=111;
str[3]='d';
str[4]='\n';
str[5]='b';
str[6]='y';
str[7]='e';
str[8]='.';
for(i=0;i<10;i++){
putchar(str[i]);
}
return 0;
}
The result of running the above program is as follows:
Four, puts function
The function of the puts function is to output the string to the display. This function has no return value. The format is as follows:
puts(str);
For example:
#include<stdio.h>
int main() {
int i;
char str[10];
str[0]='G';
str[1]='o';
str[2]=111;
str[3]='d';
str[4]='\n';
str[5]='b';
str[6]='y';
str[7]='e';
str[8]='.';
printf("%s\n\n",str);
puts(str);
return 0;
}
The result of running the above program is as follows:
Escape characters can be included in the output, for example:
#include<stdio.h>
int main() {
puts("I\nLove\nYou!");
return 0;
}
The result of running the above program is as follows: