C语言如何从stdin赋值到char ?
在C语言中,可以使用scanf函数从stdin中读取输入并赋值给char *变量。以下是一个示例代码:
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
scanf("%s", str);
printf("您输入的字符串是:%s\n", str);
return 0;
}
在上面的示例中,我们定义了一个char类型的数组str用于存储输入的字符串。然后使用scanf函数读取输入的字符串,并将其赋值给str变量。最后,我们使用printf函数输出输入的字符串。
请注意,scanf函数在读取字符串时,会自动忽略字符串中的空格。如果您需要读取包含空格的字符串,可以使用fgets函数实现:
#include <stdio.h>
int main() {
char str[100];
printf("请输入字符串:");
fgets(str, sizeof(str), stdin);
printf("您输入的字符串是:%s\n", str);
return 0;
}
在上面的示例中,我们使用fgets函数读取输入的字符串,并将其赋值给str变量。fgets函数可以读取包含空格的字符串,并指定读取的最大字符数
原文地址: http://www.cveoy.top/t/topic/iQ38 著作权归作者所有。请勿转载和采集!