Search code examples
c++stringasciistdvector

Problem with assigning characters from a std::string to a std::vector<std::string>


Problem

I tried to assign every letter of a std::string to a std::vector<std::string>. I didn't use std::vector<char>, because these characters will be mixed, e.g. 3 -> 30. Unfortunately, instead of letters in the std::vector there are ASCII codes. Interestingly, when I tried to do this with old C-style arrays, the conversion went through without a problem and I had strings in the std::string array.

Code

template <typename numTyp>
void numberAsRoman<numTyp>::convert()
{
    numberAsArray = std::to_string(number); // numberAsArray is (int) member of class 
                                            // I convert it to std::string.

    std::vector<std::string> vecOfNum;               // Make vector
    for(int i = 0; i < numberAsArray.length(); i++)  // Loop to assign
    {                                                              
        vecOfNum.push_back(std::to_string(numberAsArray.at(i))); // I assign every letter 
        std::cout << vecOfNum.at(i) << "  ";                     // to vector and print it. 
    }

    std::cout << "\n\n\n"; 
}

What I see upon execution

The vector is printing 51 and `50. I checked it, and it agrees with the ASCII codes:

51 - 3
50 - 2

Solution

  • Try this

    vecOfNum.emplace_back(1, numberAsArray.at(i)));
    

    The std::string std::to_string(char c) overload does not exist. std::string to_string(int value); is used like

    int value = numberAsArray.at(i);  // c promotes to int getting ascii code of the containing character
    vecOfNum.push_back(std::to_string(value));