C++ String to unsigned long

Hello everybody!

I´m searching a way to convert C++ string to unsigned long format.

My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>

using namespace std;

int main()
{
	string ID = "0x3F";

	unsigned long value;    // How to assign the variable "0x3F" to variable value? From string to unsigned long.
	
	// Conversion here from ID to value, but how?

	cout << value << endl; // Here the "value" would be 63 in decimal number. (0x3F) 


I´ve seen many tutorials, also from cplusplus.com but they are always talking like:

unsigned long int strtoul ( const char * str, char ** endptr, int base );

But the first parameter is char* ? Not string ? Or have I understood something wrong?

Thank you for all help!
To convert a std::string to a c-string (char*), use c_str().

http://www.cplusplus.com/reference/string/string/c_str/

I have no idea about the char** as the 2nd argument. The example here uses NULL, so I guess I would use NULL too :)

int base would be the base of your string, so for your code this would be 16. The 0x is optional if the base is 16. I guess I would recommend removing an "0x" before calling this function.

Something like this:
1
2
3
4
string ID = "10";

cout << "Base 10: " << stroul(ID.c_str(), NULL, 10) << endl;
cout << "Base 16: " << stroul(ID.c_str(), NULL, 16) << endl;


Edit: Okay, looks like the second argument would be for if you have a c_string array, which would take a little work to make from a std:string array.


Last edited on
they are always talking like:
unsigned long int strtoul ( const char * str, char ** endptr, int base );
But the first parameter is char* ? Not string ?

If your compiler is recent, you can use stoul(), which takes a string as the first parameter

http://en.cppreference.com/w/cpp/string/basic_string/stoul
Last edited on
Thank you for all help!

I did just like LowestOne said:

1
2
3
4
string ID = "10";

cout << "Base 10: " << stroul(ID.c_str(), NULL, 10) << endl;
cout << "Base 16: " << stroul(ID.c_str(), NULL, 16) << endl;



And it works perfectly!
Last edited on
Topic archived. No new replies allowed.