Assuming I have a string variable with the text string of a hexadecimal number, how can I save it to a number?
string n = "0X54";
int a = int(n);
int b = static_cast<int>(n);
It throws me the error:invalid cast from type ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ to type ‘int’
The error you receive is clear and concise: Cannot convert a
std::string
toint
. The conversion you used (static_cast
) is a type conversion; this conversion only allows conversions between certain fundamental types, conversions with classes that have conversion operators, or conversions between classes that are related by inheritance. Forstd::string
eint
, none of the above cases holds.C++ has at least three tools to convert a character string into a numeric value, apart from the (already mentioned by Xam )
std::stoi
(s
tringto
i
nteger) we have the format readingstd::stringstream
:In the code above, we told
std::stringstream
that we were going to read a hexadecimal value (std::hex
) into a variable of typeint
; would work with any integral data type.Also (since C++17) we have
std::from_chars
, which converts a closed sequence of values to a number:As of the C++11 standard there is the function
stoi
, which can be accessed by including the header<string>
.This function in its most general form has the signature:
For your example, since your string contains a hexadecimal number, it is enough to change the last parameter (which defaults to base 10 numbers) to the value 16.
Consequently, this should do the trick:
For more reference you can check the following link .