Thread: String with Spaces. HELP.

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    10

    String with Spaces. HELP.

    Why is it that if i use scanf for input of a string data type, the words entered after a space are not printed?

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Because scanf (with a basic %s format) will see spaces as "string separators".

    I'd suggest that you use fgets() to read strings with spaces. It is much easier and more safe than trying to do it with scanf().

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  3. #3
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You can also use a custom conversion specifier like %[ A-Za-z] which will capture uppercase letters, lower case letter, and spaces. %[ A-Za-z*!;] will capture all that plus *, ! or ;

    etc.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  4. #4
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    to read string using scanf till the \n char the following format could be used
    "%[^\n]"

    of course adding width specifier will be good practice as well
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. removing spaces from a string
    By bradleym83 in forum C++ Programming
    Replies: 4
    Last Post: 07-28-2005, 01:59 PM
  4. Replies: 3
    Last Post: 04-06-2005, 11:04 AM
  5. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-27-2003, 12:03 AM