C语言 C scanf 有空格问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4358383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C scanf with spaces problem
提问by user531119
Possible Duplicate:
How do you allow spaces to be entered using scanf?
可能的重复:
如何允许使用 scanf 输入空格?
printf("please key in book title\n"); scanf("%s",bookname);
printf("请输入书名\n"); scanf("%s",书名);
i inside the data like this :- C Programming
我在数据里面是这样的:- C 编程
but why output the data like this :- C
但为什么输出这样的数据:- C
lose the Programming (strings) ?
丢失编程(字符串)?
why
为什么
thanks.
谢谢。
回答by John Bode
The %sconversion specifier causes scanfto stop at the first whitespace character. If you need to be able to read whitespace characters, you will either need to use the %[conversion specifier, such as
该%s转换说明会导致scanf停在第一个空格字符。如果您需要能够读取空白字符,则需要使用%[转换说明符,例如
scanf("%[^\n]", bookname);
which will read everything up to the next newline character and store it to bookname, although to be safe you should specify the maximum length of bookname in the conversion specifier; e.g. if bookname has room for 30 characters counting the null terminator, you should write
它将读取下一个换行符之前的所有内容并将其存储到bookname,但为了安全起见,您应该在转换说明符中指定 bookname 的最大长度;例如,如果 bookname 有 30 个字符的空间计算空终止符,你应该写
scanf("%29[^\n]", bookname);
Otherwise, you could use fgets():
否则,您可以使用fgets():
fgets(bookname, sizeof bookname, stdin);
I prefer the fgets()solution, personally.
我fgets()个人更喜欢这个解决方案。
回答by Friedrich
Well booknamesurly is some kind of char ;-)
Point is that scanfin this form stop on the first whitespace character.
那么bookname粗暴是某种字符 ;-) 要点是scanf在这种形式中停止在第一个空白字符上。
You can use a different format string, but in this case, one probably should prefer using fgets.
您可以使用不同的格式字符串,但在这种情况下,人们可能更喜欢使用fgets.
scanfreally should be used for "formatted" input.
scanf真的应该用于“格式化”输入。

