How to get unsigned int as console argument?

2019-08-22 21:08发布


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

标签: c++
2条回答
欢心
2楼-- · 2019-08-22 21:29

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

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

unsigned long ul;

std::stringstream(str)>>ul;
查看更多
爷的心禁止访问
3楼-- · 2019-08-22 21:30

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 :-)

查看更多
登录 后发表回答