For those unable or unwilling to use libraries such as “atoi” or “stoi”, I experimented a bit and made a quick little program that would be able to output a number input as a string.
The code is as follows:
The code functions like this in a nutshell:
- Create a string holding the number and an integer to be given the value via the string
- A for-loop that has two local integers: digit and multiplier
- digit marks the current digit in the string to be extracted. For example, it begins with selecting digit 5, which is 2 in this case, using the statement “numberString.at(digit)”, the equivalent of “numberString.at(4). Remember that strings are arrays, and arrays start at 0, so value number 5 has the array address 4, hence the “4” in “numberString.at(4)”.
- multiplier marks what the digit is to be multiplied by. This is necessary for the integer to receive the correct sum in the end: 18362 is equal to:
(1 * 10^4) + (8* 10^3) + (3 * 10^2) + (6 * 10^1) + (2 * 10^0),
which is the same as:
10000 + 8000 + 300 + 60 + 2 = 18362.
- The for-loop adds the numbers together. In order for this to work, because the decimal system is dependent on each digit having its own magnitude depending on its relative position, each digit is multiplied by its respective position’s magnitude. For instance, to make sure it’s really understood, the number 162 has three digits. The digit 2 has a value of 2, because it’s in a position with the lowest magnitude. The digit 6 has a value of 60, because it’s in a position with a magnitude of 10^1 (10), meaning it’s multiplied by 10. The digit 1 has a value of 100, because it’s in a position with a magnitude of 10^2 (100), meaning it’s multiplied by 100. This continues ad infinitum with increasingly larger numbers that have plenty more digits. Note that the digit 2 really has a magnitude of 10^0. 10^0 is equal to 1, so its final value would be 2 * 1 = 2.
- The reason for the subtraction of 48 from the digit extracted is because ‘0’ has a value of 48 in the ASCII table, ‘1’ has a value of 49, and so on. By subtracting 48, we get the values represented by the ASCII-values in char format, allowing us to get accurate results. Here is the basic ASCII table, fetched from this web page:
Continuing, multiplier is incremented each time the loop runs, and because the program takes into account the size of the string.
- Be careful not to enter any alphabetical characters in the string, as the result will become inaccurate. The closest you can get being allowed to do this, is doing this type of conversion with hexadecimal values, using A, B, C, D, E and F.
- This cannot do floats or doubles, as they could have negative magnitude positions, i.e. values beyond the decimal point.
Tasks for newbies:
- Create a program that can fetch floats and/or doubles from strings.