Question

I am using the following code to convert Const char * to Unsigned long int, but the output is always 0. Where am I doing wrong? Please let me know.

Here is my code:

#include <iostream>
#include <vector>
#include <stdlib.h>

using namespace std;

int main() 
{
    vector<string> tok;
    tok.push_back("2");
    const char *n = tok[0].c_str();
    unsigned long int nc;
    char *pEnd;
    nc=strtoul(n,&pEnd,1);
    //cout<<n<<endl;
    cout<<nc<<endl; // it must output 2 !?
    return 0;
}
Was it helpful?

Solution 2

You need to use:

nc=strtoul(n,&pEnd,10);

You used base=1 that means only zeroes are allowed.

If you need info about integer bases you can read this

OTHER TIPS

Use base-10:

nc=strtoul(n,&pEnd,10);

or allow the base to be auto-detected:

nc=strtoul(n,&pEnd,0);

The third argument to strtoul is the base to be used and you had it as base-1.

The C standard library function strtoul takes as its third argument the base/radix of the number system to be used in interpreting the char array pointed to by the first argument.

Where am I doing wrong?

nc=strtoul(n,&pEnd,1);

You're passing the base as 1, which leads to a unary numeral system i.e. the only number that can be repesented is 0. Hence you'd get only that as the output. If you need decimal system interpretation, pass 10 instead of 1.

Alternatively, passing 0 lets the function auto-detect the system based on the prefix: if it starts with 0 then it is interpreted as octal, if it is 0x or 0X it is taken as hexadecimal, if it has other numerals it is assumed as decimal.

Aside:

  • If you don't need to know the character upto which the conversion was considered then passing a dummy second parameter is not required; you can pass NULL instead.
  • When you're using a C standard library function in a C++ program, it's recommended that you include the C++ version of the header; with the prefix c, without the suffix .h e.g. in your case, it'd be #include <cstdlib>
  • using namespace std; is considered bad practice
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top