Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Part of string conversion into integer - C++

I'm wondering if I can convert part of my string into an integer using static_cast? I know that something like atoi() exists, but should I really use it in order to converse only the first character of my string into integer?

int w;
string my_str;
getline(cin, my_str);
w = static_cast<int>(my_str[0]) - 48;

Is something like this correct? Or should I do this in another way?

like image 343
whatfor Avatar asked Jul 19 '26 10:07

whatfor


2 Answers

As long you are sure that my_str[0] contains a digit character, it's fine.

You should avoid magic numbers like 48 though, better write w = my_str[0] - '0';

The number 48 is the ASCII code numeric representation of '0'. There are other character code systems (like EBCDIC codes) and the c or c++ languages don't have an explicit notion of these, and the numerical representations can completely differ.

That said using '0' will be portable for many character code systems not just ASCII codes.

like image 179
πάντα ῥεῖ Avatar answered Jul 21 '26 00:07

πάντα ῥεῖ


There is no any need to use static_cast because in any case the integer promotion is applied to the expression my_str[0] of type char. So these two expressions

static_cast<int>(my_str[0]) - 48; 

and

my_str[0] - 48;

are equivalent.

This is correct provided that you want to convert only one character of the string. Otherwise you should use standard function stoi.

Also instead of the magic number 48 it is much better to use character literal '0'

my_str[0] - '0';

because it is more readable and clear and does not depend on used coding system. For example in EBCDIC the code of zero is 0xF0.

like image 22
Vlad from Moscow Avatar answered Jul 21 '26 00:07

Vlad from Moscow



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!