Thread: Trouble reading integer from sscanf

  1. #1
    Registered User
    Join Date
    Nov 2012

    Trouble reading integer from sscanf

    sscanf(x, "%s %d %s",, &object.price,;
    Where x is an string and and are parts of structures as is object.price. The strings work fine and if I replace %d with double it also works fine. But %d and %u seem to give either really large numbers or something completely different from what is supposed to be scanned.

    typedef union{
            char name[12];
            int price;
            category_t category;
    } object_t;
    There is another structure that connects category b to the above. changing int price to int* or unsigned int with corresponding %u in sscanf didn't help. Changing to double seems to produce the correct result however.

    I've been working on this for several hours to no avail. Please help. I don't see how it could read doubles but not integers.

  2. #2
    Registered User
    Join Date
    Sep 2012
    sscanf() (and the other function in the scanf() family) returns a very important number: the number of conversions successfully executed.
    You really should test that number for the expected value

    if (sscanf(x, "%s %d %s",, &object.price, != 3)
        fprintf(stderr, "Invalid input\n");

  3. #3
    Registered User
    Join Date
    Nov 2010
    Long Beach, CA
    object_t is not a struct, it's a union. That means name, price and category overlap, and you can't use all of them at once. This very well may be the cause of your problem. You probably want to change the word 'union' to 'struct'.

    It would help if you gave us more information. What are the contents of x? Perhaps they are not what you think they are. You should print it out immediately before calling sscanf to be sure. The definition of category_t would help as well.

    Give us the smallest, compilable example that we can use to test, and give use the input that is producing the incorrect results, the output you expect to get and what you actually get. That makes it easy for us to help you.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with reading a file in C, with fgets()/sscanf()
    By ErickN in forum C Programming
    Replies: 3
    Last Post: 04-23-2011, 10:54 AM
  2. sscanf()-getting integer from a string
    By saman_glorious in forum C Programming
    Replies: 8
    Last Post: 09-02-2010, 08:47 AM
  3. Reading integers in sscanf
    By Blasz in forum C Programming
    Replies: 1
    Last Post: 04-30-2010, 06:57 AM
  4. reading strings with spaces using sscanf
    By kotoko in forum C Programming
    Replies: 2
    Last Post: 06-14-2008, 05:06 PM
  5. Problems reading formatted input with sscanf
    By Nazgulled in forum C Programming
    Replies: 17
    Last Post: 05-10-2006, 12:46 AM