scanf delimiter problem

This is a discussion on scanf delimiter problem within the C Programming forums, part of the General Programming Boards category; Hi there, I wrote the following code, what I intend to do is to use '!' as delimiter to save ...

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    5

    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);
    fflush(stdin);
    getchar();
    }

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,668
    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
    Posts
    5
    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, 05:15 PM
  2. Problem with scanf float..
    By aydin1 in forum C Programming
    Replies: 6
    Last Post: 03-06-2005, 12:35 PM
  3. scanf problem
    By gsoft in forum C Programming
    Replies: 3
    Last Post: 01-04-2005, 11:42 PM
  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, 12:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21