开发者

C scanf with spaces problem [duplicate]

开发者 https://www.devze.com 2023-01-28 18:37 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: How do you allow spaces to be entered using scanf?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

How do you allow spaces to be entered using scanf?

printf("please key in book title\n"); scanf("%s",bookname);

i inside the data like thi开发者_StackOverflow社区s :- C Programming

but why output the data like this :- C

lose the Programming (strings) ?

why

thanks.


The %s conversion specifier causes scanf to 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

 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

 scanf("%29[^\n]", bookname);

Otherwise, you could use fgets():

 fgets(bookname, sizeof bookname, stdin);

I prefer the fgets() solution, personally.


Use fgets() instead of scanf()


Well bookname surly is some kind of char ;-) Point is that scanf in this form stop on the first whitespace character.

You can use a different format string, but in this case, one probably should prefer using fgets.

scanf really should be used for "formatted" input.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号