Search code examples
c++ascii

How to understand logic behind these functions?


#include <iostream>
#include <cstring>

using namespace std;

long digitToLong(char c) { // function returns the value type long (c - '0') and takes the char c as an argument. 
    return c - '0';  // c is equal to (text[i]) and 0 is the code ascii assigned as a nr 0.
}

long toLong(string text) {. /* takes a text that represents a number and then transfers              the text into a number.*/
    long result = 0;  

    for (int i = 0; i < text.length(); i++) { /* for loop that iterates through every character included in a text length.*/
        result *= 10;  
        result += digitToLong(text[i]); 
    }

    return result;
}


int main() {
    char number[] = "0123456789";

    cout << (toLong("0") == 0) << endl; 
    cout << (toLong("1") == 1) << endl;
    cout << (toLong("2") == 2) << endl;
    cout << (toLong("5") == 5) << endl;
    cout << (toLong("12") == 12) << endl;
    cout << (toLong("123") == 123) << endl;
    cout << (toLong("12345") == 12345) << endl;
}

In the code above my teacher used the method of string-to-long conversion where we compare each character to its ASCII values and then get the value of that numeric character. I'm trying to picture the process of this conversion and I'm stuck on two lines of the code above therefore I'm direct my question to the StackOverflow community, hoping this can be answered. The line result *= 10; and result += digitToLong(text[I]) could be also written as a  result = result * 10 + (c - '0') Is that correct? Why do we need to multiply result by 10? I assume it's because in decimal, multiplying by 10 moves all digits to the left changing its values. How it applies in this code in reality? What is the "mechanic" behind it?

What exactly is assigned to c in this code? How to read it? Ic c equal to text[I]? What is under text[I] then? an iteration of the for loop? How to count it? I really try to understand the logic of the program (especially the functions) but some parts are unbearable yet.

I did my research before best as I could and I really hope my question could be answered.


Solution

  • Q1. Whats the purpose and mechanism of the code?

    long toLong(string text) {. /* takes a text that represents a number and then transfers              the text into a number.*/
        long result = 0;  
    
        for (int i = 0; i < text.length(); i++) { /* for loop that iterates through every character included in a text length.*/
            result *= 10;  
            result += digitToLong(text[i]); 
        }
    
        return result;
    }
    

    You are correct. This is performed because you get the digits one-by-one from the left (most-significant-digit) but you need to insert it from the right.

    Lets try to break it down.

    • First time entering the loop,
      • Currently, result = 0, so the multiply by 10 does nothing.
      • Then, text[i] gets 1 digit, in character form, at the first position from left, since i = 0 currently.
    • All other enterings
      • Multiplying by 10 effictivly moves all the numbers to the left. The position where the new digit should be is now a 0.
      • Since digitTolong() get only 1 digit number, simply adding the number to result is same as pasting it onto the rightmost position.

    Q2. What does c and text[i] do here?

    I assume you know about an array, or a vector. The string acts the same, except this time, its a bunch of char (characters). When you use string[i], its simply gets you the i-th character from the left, starting from zero.

    For example, you call str[3] on string str = "abcdefg", its basically 'd'. Then, you pass it in to digitToLong().

    Lastly, you perform a subtraction between characters. How do you do it?

    In the ACSII code table (google it!), you can see that when you have a charatcter 0, its actually stored internally as the number 48. '1' is 49, '2' is 50, and so on.
    Using this property, minusing '0' actually gets us the correct value of the digit (for example, '1' - '0' actually does 49 - 48 which gets you 1.), thus you see the character subtraction in the function.

    Hope you can understand now.