Ernest
Ernest

Reputation: 37

Why was the C++ string converted to int?

In the following code, I can not understand why the string is converted to int in this way.

Why is it using a sum with 0 ?

string mystring; 
vector<int> myint; 
mystring[i+1]=myint[i]+'0';

Upvotes: 2

Views: 122

Answers (3)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22214

This is an efficient, old school and dangerous method to get a char representation of a single digit. '0' will be converted to an int containing its ASCII code (0x30 for '0') and then that is added to myint[i]. If myint[i] is 9 or lower, you can cast myint[i] to a char you will get the resulting digit as text.

Things will not go as expected if you add more than 9 to '0'

You can also get a number from its char representation :

char text = '5';
int digit = text - '0';

Upvotes: 2

Semyon Burov
Semyon Burov

Reputation: 1172

The '0' expression isn't string type, it's char type that stores characters of ASCII and also can represent numbers from 0 to 255. So, in arithmetic operations char behaves like integer type.

In C strings a represent as arrays of char: static (char str[N]) or dynamic (char *str = new char[n]). String literals puts into double quotes ("string"). So, '0' is char and "0" is char[1]

Upvotes: 1

Mureinik
Mureinik

Reputation: 311018

This code converts an int (presumably a digit) to the character that represents it.

Since characters are sequential, and chars can be treated as integers, the character representing a certain digit can, in fact, be described by its distance from '0'. This way, 0 turns turn to the character '0', '5' is the character that is greater than '0' by five, and so on.

Upvotes: 2

Related Questions