Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal string to char

Tags:

c++

string

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.

like image 331
Sinjuice Avatar asked Dec 30 '25 14:12

Sinjuice


2 Answers

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);
like image 187
Salvatore Previti Avatar answered Jan 02 '26 03:01

Salvatore Previti


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;
like image 40
Jon Avatar answered Jan 02 '26 03:01

Jon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!