How to input spaces in a C language string?
In the C language, you can use the scanf function or gets function to input strings containing spaces.
When using the scanf function to input a string, you can use the “%[^\n]s” format specifier, which means inputting all characters except for the newline character. Below is an example code:
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
scanf("%[^\n]s", str);
printf("输入的字符串是:%s\n", str);
return 0;
}
When using the gets function to input a string, you can directly read a complete line of text. Example code is provided below:
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
gets(str);
printf("输入的字符串是:%s\n", str);
return 0;
}
It is worth noting that the gets function has security issues and is not recommended for use. It is suggested to use the fgets function instead, which allows for specifying the maximum number of characters to read and prevents buffer overflow. An example code is as follows:
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
printf("输入的字符串是:%s\n", str);
return 0;
}