Danny
Danny

Reputation: 9624

C++ Converting color value String to int

I have tried to convert a color code by reading a file, retrieve the color code and store it as a string. This works, but when I tried to just simply convert it to an int, it doesn't work - always getting 0 when I do a cout.

string value = "0xFFFFFF";
unsigned int colorValue = atoi(value.c_str());
cout << colorValue << endl;

as you can see, the color I've got is 0xFFFFFF, but converting it to an int will only give me 0. Can someone please tell me what I'm missing or what i'm doing wrong?

Thanks

Upvotes: 2

Views: 2757

Answers (2)

amrith92
amrith92

Reputation: 220

As @BartekBanachewicz says, atoi() is NOT the C++ way of doing this. Leverage the power of C++ streams and use std::istringstream to do it for you. See this.

An excerpt:

template <typename DataType>
DataType convertFromString(std::string MyString)
{
    DataType retValue;
    std::stringstream stream;
    stream << std::hex << MyString; // Credit to @elusive :)
    stream >> retValue;
    return retValue;
}

Upvotes: 0

jwueller
jwueller

Reputation: 30996

I suggest using stringstreams:

std::string value = "0xFFFFFF";
unsigned int colorValue;
std::stringstream sstream;
sstream << std::hex << value;
sstream >> colorValue;
cout << colorValue << endl;

Upvotes: 2

Related Questions