How to input a string using char in the C language?
In C language, you can use character arrays to input strings. The specific steps are as follows:
- Declare a character array to store the input string. The size of the array should be determined based on the actual needs, for example, you can declare a character array of size 100 to store shorter strings.
char str[100];
- To receive input strings using the scanf function without causing buffer overflow, use the %s format specifier with the qualifier %Ns, where N is the size of the character array minus one.
scanf("%99s", str);
- The input string will be assigned to the character array ‘str’ and automatically have a null character ‘\0’ added to the end as the end marker of the string.
Here is the complete sample code:
#include <stdio.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%99s", str);
printf("输入的字符串是:%s\n", str);
return 0;
}
When running the program, users will be prompted to input a string, which will then be printed out.