Sinjuice
Sinjuice

Reputation: 562

Decimal string to char

Is there a way to convert numeric string to a char containing that value? For example, the string "128" should convert to a char holding the value 128.

Upvotes: 2

Views: 1324

Answers (4)

MSN
MSN

Reputation: 54604

It depends. If char is signed and 8 bits, you cannot convert "128" to a char in base 10. The maximum positive value of a signed 8-bit value is 127.

This is a really pedantic answer, but you should probably know this at some point.

Upvotes: 1

Jack Edmonds
Jack Edmonds

Reputation: 33171

You can use atoi. That will get you the integer 128. You can just cast that to a char and you're done.

char c = (char) atoi("128");

Upvotes: 0

Jon
Jon

Reputation: 437376

There's the C-style atoi, but it converts to an int. You 'll have to cast to char yourself.

For a C++ style solution (which is also safer) you can do

string input("128");
stringstream ss(str);
int num;
if((ss >> num).fail()) { 
    // invalid format or other error
}

char result = (char)num;

Upvotes: 4

Salvatore Previti
Salvatore Previti

Reputation: 9050

Yes... atoi from C.

char mychar = (char)atoi("128");

A more C++ oriented approach would be...

template<class T>
    T fromString(const std::string& s)
{
     std::istringstream stream (s);
     T t;
     stream >> t;
     return t;
}

char mychar = (char)fromString<int>(mycppstring);

Upvotes: 5

Related Questions