Thread: Getting scaf to accept strings with spaces in them?

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    145

    Getting scaf to accept strings with spaces in them?

    How do I get scanf to accept strings with spaces in them, for instance 'Hello World,' whereby it'll take the whole sentence and not just the first word.

    Thanks

  2. #2
    Registered User
    Join Date
    Oct 2005
    Posts
    38
    scanf("%s %s", variables);

    but then you need to know how many words there are going to be.

    use

    gets, or fgets

    Code:
    char string[256];
    fgets(string, sizeof(string), STDIN);

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    145
    Is gets a reliable function to use? I heard its not. Is it reliable to use in coursework?

  4. #4
    & the hat of GPL slaying Thantos's Avatar
    Join Date
    Sep 2001
    Posts
    5,681
    Never ever use gets(). Use fgets() instead.

  5. #5
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >for instance 'Hello World,' whereby it'll take the whole sentence and not just the first word.
    How do you end a sentence? What you want to do moves into the realm of advanced scanf usage, where you'll be relying heavily on scansets. To read an entire line with scanf, assuming a buffer of size 1024, you could do this:
    Code:
    scanf ( "%1023[^\n]", buffer );
    To read a whole sentence, you stop at the first sentence terminating punctuation character:
    Code:
    scanf ( "%1023[^.?!]", buffer );
    Note that in both cases, the character that scanf stops at is left in the stream. Of course, for some reason a lot of people have trouble getting scanf right, so you'd be better off using fgets and then parsing as necessary.

    >fgets(string, sizeof(string), STDIN);
    stdin isn't capitalized in standard C.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Tabs or Spaces
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 46
    Last Post: 04-08-2007, 11:45 AM
  2. How to make char array accept spaces
    By izah in forum C++ Programming
    Replies: 1
    Last Post: 10-10-2006, 02:11 PM
  3. Strings allowing spaces?
    By Dan17 in forum C++ Programming
    Replies: 13
    Last Post: 02-04-2006, 03:15 PM
  4. saving a CString to binary file with trailing spaces
    By nineofhearts in forum C++ Programming
    Replies: 12
    Last Post: 01-03-2006, 11:53 AM
  5. damn strings
    By jmzl666 in forum C Programming
    Replies: 10
    Last Post: 06-24-2002, 02:09 AM