#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    3
    Rep Power
    0

    Arrow Array not accepting spaces?


    For some reason when a user inputs something with spaces (e.g. "Hello World"), the following code will print "You wrote: Hello".

    Code:
    int main ( void ) {
    	char str[25]; 
    	printf("Type something:\n");
    	scanf("%s", str);
    	printf("You wrote: %s\n", str);
    	return 0;
    }
    Shouldn't it print "Hello World"?
  2. #2
  3. I'm Baaaaaaack!
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jul 2003
    Location
    Maryland
    Posts
    5,538
    Rep Power
    243
    RTFM. Try using fgets() instead.

    My blog, The Fount of Useless Information http://sol-biotech.com/wordpress/
    Free code: http://sol-biotech.com/code/.
    Secure Programming: http://sol-biotech.com/code/SecProgFAQ.html.
    Performance Programming: http://sol-biotech.com/code/PerformanceProgramming.html.
    LinkedIn Profile: http://www.linkedin.com/in/keithoxenrider

    It is not that old programmers are any smarter or code better, it is just that they have made the same stupid mistake so many times that it is second nature to fix it.
    --Me, I just made it up

    The reasonable man adapts himself to the world; the unreasonable one persists in trying to adapt the world to himself. Therefore, all progress depends on the unreasonable man.
    --George Bernard Shaw
  4. #3
  5. Contributing User

    Join Date
    Aug 2003
    Location
    UK
    Posts
    5,109
    Rep Power
    1802
    In scanf() whitespace is a string delimiter.
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    5
    Rep Power
    0
    Originally Posted by SGilligan
    For some reason when a user inputs something with spaces (e.g. "Hello World"), the following code will print "You wrote: Hello".

    Code:
    int main ( void ) {
    	char str[25]; 
    	printf("Type something:\n");
    	scanf("%s", str);
    	printf("You wrote: %s\n", str);
    	return 0;
    }
    Shouldn't it print "Hello World"?

    use scanf("%[^\n]s",str); instead of scanf("%s", str);
    because as soon as you press spacebar compiler places \0 at that position.


    or
    use gets(str) statement after including string.h file

    Comments on this post

    • dwise1_aol disagrees : About the gets, which the documentation, if you were to RTFM, tells you to stop using and to use fgets(stdin) instead. Buffer overflow vulnerabilities.

IMN logo majestic logo threadwatch logo seochat tools logo