By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,501 Members | 2,871 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,501 IT Pros & Developers. It's quick & easy.

in the printf the program remove all the strings after the space why???

P: 18
Expand|Select|Wrap|Line Numbers
  1. #include<stdio.h>
  2. void num(char arr[100])
  3. {
  4. int i=0, count=1;
  5. while (arr[i]!='\0')
  6. {
  7. if (arr[i]==' ')
  8. {count++;}
  9. i++;
  10. }
  11. printf("%d",count);
  12. }
  13. int main()
  14. {
  15.  
  16. char data [100];
  17.  
  18. scanf("%s",&data);
  19. printf("%s",data);
  20. num(data);
  21. return 0;
  22. }
try to inter programming language
in the printf in the main it will printf programming only and remove the rest
Dec 7 '10 #1
Share this Question
Share on Google+
9 Replies


Banfa
Expert Mod 5K+
P: 8,916
No that is not printf getting it wrong, that is scanf behaving exactly as specified.

scanf uses any white space as a delimiter so if you ask scanf for a string and enter "programming language" it will use the space as a delimiter and return "programming" which printf then correctly outputs.

If you want to get a whole line including spaces using the end of line as a delimiter then use the function fgets.
Dec 7 '10 #2

P: 18
how can u give me an example
Dec 7 '10 #3

Banfa
Expert Mod 5K+
P: 8,916
Perhaps you could try typing "fgets" into your browser search engine?
Dec 7 '10 #4

P: 18
okai thanks
Dec 7 '10 #5

Expert 100+
P: 2,400
Better than typing 'fgets' into the browser ...
  1. Look for "bytes > c/c++ > c/c++ questions" in small print near the top of this browser page (just above the thread title).
  2. Click on "c/c++ questions".
  3. Then click on the first question: "PLEASE READ FIRST: Useful Links and Posting Guidelines"
  4. Scroll down to the second message in this thread. It contains Important Links.
  5. Click on either of the "C and C++ library reference" links.
  6. Now search for fgets.
Dec 7 '10 #6

P: 18
when i replace the space between the words by tab it didn't work in a right way
any help in this !!
Dec 11 '10 #7

Banfa
Expert Mod 5K+
P: 8,916
There is no reason why it would work any differently, tab is also a white space character.
Dec 13 '10 #8

Expert 100+
P: 2,400
Refer to reply #2. Use fgets. Don't use scanf.
Dec 13 '10 #9

P: 14
Options to get rid of current problem:
gets() function instead of scanf [although this is often frowned upon]
fgets() function instead of scanf

or continue using scanf but clear the buffer with a while loop.
Google: clean buffer after scanf for more details on this.
Dec 17 '10 #10

Post your reply

Sign in to post your reply or Sign up for a free account.