Your fx[0]
and fx[3]
variables are of type char
(which is an integer type in C++). However, the actual values in those two elements of your fx
string will be representations of the digits, 6
and 2
, not the numerical values of those digits.
Very often, those representations will be ASCII codes (but that's not required); however, what is required is that the representations of the digits 0
thru 9
have contiguous, sequential values. Thus, by subtracting the value of the digit, 0
, we can convert to their numerical representations.
In your case, the following line will do the conversion:
int part1 = (fx[0]-'0') * (fx[3]-'0');
The reason why you see the correct values when printing fx[0]
and fx[3]
is because the version of the cout <<
operator that takes a char
argument is designed to print the represented character (not its 'ASCII' code); however, the cout <<
operator for an int
type (like your part1
) will print the actual value represented internally. (Try changing one of your lines to cout << (int)fx[0] << endl;
to see the difference.)
P.S. Don't forget the #include <string>
header – some implementations do that implicity inside the <iostream>
header, but don't rely on that!