I'm having sort of a bizarre problem. What I'd like to do is accept a user integer and store each digit in an array. For example- let's say the number is 12345, I want to store each digit separately in it's own position in an array (so, 1 in position 0, 2 in position 1, etc.) The numbers have to be able to be recalled and used in mathematical calculations.
So, this is what I have in simplified version so far:
unsignedlongint UserNum;
char Storage[99];
int Position=0,
exponent;
cin >> UserNum; //let's say it's 12345
sprintf(Storage,"%d", UserNum); //I think this is where the problem is
exponent = strlen(Storage) - 1;
while (exponent >= 0)
{
cout << "position= " << Position << endl //simply for reference
<< "Storage[Position]= " << Storage[Position] << endl;
//interestingly, it shows the correct value for the cout of Storage[Position]
cout << "Storage[Position] * 2 = " << Storage[Position] * 2 << endl;
//The problem begins here when trying to do math
exponent -= 1;
Position += 1;
}
When it tries to do math with the Storage[Position] (in this example multiplying times 2), it yields bizarre answers. For example when it shows Storage[Position] = 1, and then it is multiplied by 2, the answer should be 2 but it prints 98??? Idk how this is happening but I feel like it has something to do with char/int problems. Help please??
characters are represented by their ASCII counterparts. What's happening is that your integer is 1, but the character for '1' in ASCII is actually == 49.
Try this to see what I mean:
1 2
cout << int( 1 ) << endl; // prints the integer 1 (output: "1")
cout << int( '1' ) << endl; // prints the character '1' (output: "49")
When you do math on the ASCII character code, it's converting it to another ASCII code.
49 * 2 = 98, and the ASCII character for 98 is 'b'
One solution here is to convert your chars to integers. This is done simply enough by subtracting '0' from them:
Also, any ideas on how to convert actual alphabetical characters entered by the user (a,b,c) into numbers as in hexadecimal to decimal conversions but for all letters of the alphabet? So that A-Z would represent the corresponding number after 0-9. It's in the same code as well.