How to input strings in the C language?
In the C language, strings can be input in several ways:
- Using a character array: You can declare a character array large enough to store a string, and then use the scanf function or gets function to read the string from standard input. For example:
#include <stdio.h>
int main() {
char str[100]; // 声明一个字符数组,大小为100
printf("请输入字符串:");
scanf("%s", str); // 使用scanf函数读取字符串
printf("输入的字符串是:%s\n", str);
return 0;
}
- By using pointers, you can declare a pointer variable, allocate a certain amount of memory space using the malloc function, and then read in a string from standard input using the scanf or gets function. For example:
#include <stdio.h>
#include <stdlib.h>
int main() {
char *str; // 声明一个指针变量
str = (char *)malloc(100 * sizeof(char)); // 分配100个字符大小的内存空间
printf("请输入字符串:");
gets(str); // 使用gets函数读取字符串
printf("输入的字符串是:%s\n", str);
free(str); // 释放内存空间
return 0;
}
It is important to ensure that the allocated memory space is large enough when using the gets function to avoid overflow. Additionally, since the gets function has been marked as unsafe, it is recommended to use the safer fgets function instead.