Hi I\'m trying to pull one member of a string and set that equal to an int. I understand that you can\'t simply put the int equal to the string value but I\'m not sure how else
This is a common mistake. Strings
are merely arrays of characters, and a (basic) character is a number between 1 and 127 (excluding some special control characters). "0" as a char
is represented by the number 48, and hence "0" really equals 48, since "0" is a char
and 48 is an int
, and they are different ways of representing the same basic data.
Luckily for you, there's a fairly easy way to solve your problem: Just convert each char
to its equivalent int
:
cout << strzip[1] << " is equal to: " << strzip[1] - '0' << endl;
Please notice that you cannot use cstdlib's atoi()
function here since it will convert your whole string to a number, and in your case that will cause the loss of your leading zeroes, and probably overflow your int
.