2

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 this :- C Programming

but why output the data like this :- C

lose the Programming (strings) ?

why

thanks.

Community
  • 1
  • 1
user531119
  • 55
  • 1
  • 2
  • 3

3 Answers3

20

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.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
John Bode
  • 119,563
  • 19
  • 122
  • 198
4

Use fgets() instead of scanf()

Prasoon Saurav
  • 91,295
  • 49
  • 239
  • 345
0

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.

Friedrich
  • 5,916
  • 25
  • 45