Why is this character put into the vector as an integer?

Viewed 69

I'm trying to put a character on the stack, but it is putting the ASCII integer value of the character. What is causing this and how can I get an actual character onto the stack?

Here is some simple code to show what I mean:

#include <iostream>
#include <vector>
#include <string>

int main()
{
    std::vector<std::string> v;
    std::string s = "ABCDEF";

    char c = s[0];

    v.push_back(std::to_string(c));

    std::cout << v[0] << std::endl;

}
1 Answers

std::to_string doesn't have a conversion from char, but it does have a conversion from int. So c will implicitly be converted to an int with the corresponding ASCII value, and this is converted to a std::string.

If you want to push_back the character c as a std::string, you can do:

v.push_back({c});

Here's a demo.

Related