Thread: sscanf() issue

  1. #1
    Registered User
    Join Date
    Dec 2012
    Posts
    21

    sscanf() issue

    I'm trying to get the number out of the argv[1] string.

    Code:
    argv[1] = -w50
    line of code I'm using:

    Code:
    sscanf(argv[1], "%d", &columnWidth);
    if I check the return value of the sscanf() it is 0, indicated no numbers were found. Does the presence of the '-' mess sscanf() up?

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    More the presence of the w (-50 would just be, well, -50). There are libraries out there specifically for dealing with command-line options, if that's feasible for you; if you do want to roll your own, you have to remember that there is an actual option there (presumably the w means something and as such must be processed), and then you can worry about what's after the letter.

  3. #3
    Registered User
    Join Date
    Dec 2012
    Posts
    21
    Yes, the '-w' is essential. What command would you recommend to extract the number from the string?

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    If you are parsing w (for instance), which you know is a single letter command that must be followed immediately by a number, then your number is at argv[1]+2, which would therefore be your first argument to sscanf. (Note well, though: if you allow them to type "-w 50" as well as "-w50", then argv[1]+2 would be a '\0' character, and the number would be in argv[2].)

  5. #5
    Registered User
    Join Date
    Dec 2012
    Posts
    21
    Thanks! Got it working

  6. #6
    Registered User
    Join Date
    Nov 2012
    Posts
    1,393
    If you want to expand on this with a library, I would take a look at popt. There's also getopt, but popt is easier to use in my opinion. For your example it would let you specify that -w is a paramter that accepts an argument and you can even do things like specify help text to go with it or to allow alternate spellings such as

    Code:
    mycommand -w50
    mycommand -w 50
    mycommand --width=50

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. bandwidth issue / network issue with wireless device communication
    By vlrk in forum Networking/Device Communication
    Replies: 0
    Last Post: 07-05-2010, 11:52 PM
  2. sscanf issue
    By DKING89 in forum C++ Programming
    Replies: 4
    Last Post: 04-23-2008, 01:51 AM
  3. sscanf help
    By abulreesh in forum C Programming
    Replies: 3
    Last Post: 12-10-2006, 11:03 AM
  4. annoying validation issue with sscanf
    By Axel in forum C Programming
    Replies: 15
    Last Post: 10-24-2005, 09:08 AM
  5. sscanf
    By mickle in forum C Programming
    Replies: 3
    Last Post: 01-10-2003, 03:30 PM