changing list of character to list int in C++

i try to change from string to list of char, than list of char change to list int. here is my code

int main() {
    std::string int1 = "1122334455";
    std::list<char> listChars(int1.begin(), int1.end());
    std::list<int> intList(listChars.begin(), listChars.end());
    for(const auto& elem: intList){
        std::cout << elem << " ";
    }
}

The result of this is

49 49 50 50 51 51 52 52 53 53  

not

1 1 2 2 3 3 4 4 5 5 

the second method i try to use is

void printListInt(std::list<int>& listInt){
    for(int i:listInt){
        std::cout << i;
    }

    std::cout << std::endl;
}

int main() {
// make string "Hello World" and string "1122334455"
std::string str1 = "Hello World";
std::string int1 = "1122334455";

std::list<char> listChars(str1.begin(), str1.end());
std::list<char> listCharInt(int1.begin(), int1.end());

std::list<int> listInt(listCharInt.begin(), listCharInt.end());
printListInt(listInt);
}

I understand that it has to -48 to show the expected result, but is there possibility that i don’t use for to recalculate list int?

Answer

Yes, the output is correct because you had declared a string i.e, std::string int1 = "1122334455"; and then you are trying to print it as integer then the compiler will automatically typecast it according to the ASCII value of all characters of the string.

ASCII value of “0” is 48

ASCII value of “1” is 49

ASCII value of “2” is 50

ASCII value of “3” is 51

. . ASCII value of “9” is 57

So you are getting the first output as

49 49 50 50 51 51 52 52 53 53 Because it’s being printed after typecasting from char/string to int.

If you want to print 1 1 2 2 3 3 4 4 5 5 then there are different approach to achieve that, here is one of them

#include <bits/stdc++.h>
using namespace std;

int main()
{
    std::string int1 = "1122334455";
    // std::list<char> listChars(int1.begin(), int1.end());
    std::list<char> intList;
    for (char c: int1) {
        intList.push_back(c);
    }
    for(const auto& elem: intList){
        std::cout << elem << " ";
    }

    return 0;
}

OR, if you print or store the entire string into Integer List then simply subtract with the ascii value of 0 (i.e, 48)

#include <bits/stdc++.h>

int main() {
    std::string int1 = "1122334455";
    std::list<char> listChars(int1.begin(), int1.end());
    std::list<int> intList(listChars.begin(), listChars.end());
    for(const auto& elem: intList){
        std::cout << elem-48 << " ";
    }
}