### How to assign an element in a string to a variable?

So basically I'm extremely confused. When debugging my code I am using a string 'amountd' which is input by the user in the beginning of the program. The input has to be a two digit number and for my example lets say I'm using 20. I have debugged the following code:

int k=0, w=0;
cout << amountd[0];
cout << "x";
cout << amountd[1];

The x is just to separate the two clearly. Basically what I'm trying to do is assign 2 to the variable k and 0 to the variable w. When I output amound[0] it outputs the number 2. When I output amountd[1] it outputs the number 0. However, if I were to type amountd[0] = k and then output k it would output a random number (48 I believe it was). And the same with w. Why is it that amound[0] is clearly 2 and when I set it equal to something it has a problem?
`amountd[0] = k;`
This will assign the value of k to amountd[0]. You probably meant to do it the other way around.

`k = amountd[0];`
If you output k now it will still not print 2 because the value of amountd[0] is '2' (char) which is different from 2 (int). The character 2 has ASCII number 50, so if ASCII encoding is used the value of k would be 50. To fix this you can subtract it with '0' to get the number you want.
`k = amountd[0] - '0';`
Last edited on
I literally love you.
Topic archived. No new replies allowed.