c语言输入字符串有空格怎么办

char str[50];
printf("输入一段字符串:");
fgets(str,50,stdin);

采用fgets输入可以识别空格,如输入hello world,输出hello world

若采用scanf,空格就相当于一个结束符,识别不了
如输入hello world,只能输出hello

只不过用fgets输入的话,结尾会多一个‘\0’,如hello world字符串长度为12
scanf的话,如hello,结尾没有‘\0’,字符串长度为5

猜你喜欢

转载自blog.csdn.net/qq_44752641/article/details/106118698