I have the following character array:
char caracteres[10] = {'1', '2'};
And the following uint8_t
(its size is 1 byte):
uint8_t resolucion;
What I want is to store the 12 (as a number) inside the variable resolucion
. I've tried a few things but they haven't worked for me. Any suggestion?
Assuming you have this:
If you haven't already, you should end the string with
'\0'
:Which would be equivalent to this:
Passing to integer is as simple as using a loop:
That is, it iterates through the sequence of characters and subtracts the digit from each one
'0'
(don't forget that the character is the representation of a number). Reviewing an ASCII table it is easy to see that:You can convert a character string to a number with the utility
std::stoi
(s
tringto
i
nteger) present in the header<string>
:Note that it
std::stoi
returnsint
nouint8_t
, so data narrowing could occur, but if yourresolución
always going to fit in 8bits it shouldn't be a problem.Also keep in mind that passing
std::stoi
non-translatable values to number can throw an exceptionstd::invalid_argument
.