How to input characters in the C language?
In C language, you can use the scanf function to input characters.
#include <stdio.h>
int main() {
char ch;
printf("请输入一个字符:");
scanf("%c", &ch);
printf("您输入的字符是:%c\n", ch);
return 0;
}
In the example above, we first declare a variable ‘ch’ of type char to store the input character. We then use the printf function to prompt the user to enter a character. Next, we use the scanf function to read the character input by the user and save it to the ‘ch’ variable, using %c as the format specifier and the & operator to get the variable’s address. Finally, we use the printf function to output the character entered by the user.
Please note that the scanf function will ignore spaces, tabs, and newlines when reading characters. If you need to read a space or other special character, you can use the %c format specifier.
We can also use the getchar function to read characters one by one.
#include <stdio.h>
int main() {
char ch;
printf("请输入一个字符:");
ch = getchar();
printf("您输入的字符是:%c\n", ch);
return 0;
}
In the example above, the getchar function is used to read a single character and save it in the variable ch. The printf function is then used to display the character inputted by the user.
When using the getchar function to read characters, it reads the first character in the input buffer and then removes it from the buffer. To read multiple characters, you can use a loop combined with the getchar function to read each character.