Thread: scanf delimiter problem

  1. #1
    Registered User
    Join Date
    Nov 2001

    Unhappy scanf delimiter problem

    Hi there,

    I wrote the following code, what I intend to do is to use '!' as delimiter to save string to different variables, however, I found that all the characters include '!' save to first variable "name", would you please give me a hand. Thanks a lot.

    #include <stdio.h>

    int main()
    char name[128];
    char address[128];
    char phone[16];

    scanf("%s!%s!%s!", &name, &address, &phone);
    printf("%s %s %s", name, address, phone);

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    The edge of the known universe
    The delimiter with %s is always white space - you can't change it

    To do what you want, you must use the scan-set feature

    Like so
    scanf("%[^!]!%[^!]!%[^!]!", name, address, phone);

    1. You don't need the & when your variables are already arrays.
    2. %[^!] is like %s, except it will read all characters upto the next !

    > fflush(stdin);
    This doesn't work on all platforms

    It's generally better to do this
    char buff[BUFSIZ];
    fgets( buff, sizeof(buff), stdin );
    sscanf( buff, "%[^!]!%[^!]!%[^!]", name, address, phone);

    Since fgets reads a newline, the trailing newline problem (caused by scanf) disappears.

  3. #3
    Registered User
    Join Date
    Nov 2001
    you are the man! many thanks

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with RPC and scanf
    By Ricardo_R5 in forum C Programming
    Replies: 11
    Last Post: 01-08-2007, 06:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 01:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-05-2005, 12:42 AM
  4. problem with looping scanf
    By crag2804 in forum C Programming
    Replies: 6
    Last Post: 09-12-2002, 08:10 PM
  5. scanf problem
    By Flikm in forum C Programming
    Replies: 2
    Last Post: 11-05-2001, 01:48 PM