0


I'm trying to pass an unsigned int value via console argument to my program.

what have I tried yet:
first: check if argc is 2, otherwise error

if there is a second value I tried to convert this value with:

strtoul(argv[1], NULL, 0)

So when I pass "100", i get "1"
What am I doing wrong?

br
Sagi



€: passed a wrong argument to my function, found the mistake, thanks guys

Sagi
  • 783
  • 1
  • 8
  • 17

2 Answers2

4

It's a little hard to tell without seeing the actual code but you can use this as a baseline:

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
    char *pCh;
    unsigned long unlong = 42;

    // Check enough arguments.

    if (argc != 2) {
        puts ("Not enough arguments");
        return 1;
    }

    // Convert to ulong WITH CHECKING!

    unlong = strtoul (argv[1], &pCh, 10);

    // Ensure argument was okay.

    if ((pCh == argv[1]) || (*pCh != '\0')) {
        puts ("Invalid number");
        return 1;
    }

    // Output converted argument and exit.

    printf ("Argument was %ld\n", unlong);
    return 0;
}

Transcript follows:

pax> ./testprog 314159
Argument was 314159

If that's not enough to help out, I suggest you post the shortest complete program that exhibits the problem, then we can tell you in excruciating detail what's wrong with it :-)

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • thanks, as I can see I'm doing the same thing in my code... `if (argc != 2)` and after this `uiValue = strtoul (argv[1], NULL, 0);` – Sagi Oct 31 '12 at 09:03
  • @Sagi, then post your complete code in the question. That's the only way we'll be certain. Alternatively, type in my code _exactly_ (copy'n'paste) to check if it works in your environment. – paxdiablo Oct 31 '12 at 09:04
  • copied your code and it worked! also found my mistake did everything is own functions and passed the wrong param :/ – Sagi Oct 31 '12 at 09:10
  • @Sagi, the question will _still_ be far more useful to future generations if you put your original code in the question. Otherwise, it'll probably get delete since the question is lacking enough info to be useful. – paxdiablo Oct 31 '12 at 09:11
0

Your method should work. Alternatively, you can use stringstream:

std::string str(argv[1]);

unsigned long ul;

std::stringstream(str)>>ul;
P.P
  • 117,907
  • 20
  • 175
  • 238