3

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;

}
WolfyDoo
  • 143
  • 8
  • 1
    What does your C++ textbook's description of `std::to_string` say, about this? – Sam Varshavchik Oct 12 '20 at 21:27
  • 1
    I don't have a textbook. – WolfyDoo Oct 12 '20 at 21:28
  • Well, you need to get one. C++ is the most complicated general purpose programming language in use today. It cannot be learned from Google searches, random Youtube videos, or various competitive code/hacking web sites, that nobody cares about. The only way to learn C++ [is with a good textbook](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). It's going to be far more productive to proceed, one textbook chapter at a time, with practice examples, to learn C++ step by step, then to have wait for hours or days, for someone to answer on Stackoverflow. – Sam Varshavchik Oct 12 '20 at 23:04
  • I really appreciate your input @SamVarshavchik, but first of all, I never had to wait longer than 20 minutes for someone to respond to me on Stackoverflow. Secondly, I'd like to learn C++ in the way I feel most comfortable and a textbook isn't for me. I never learned fast that way. I feel like I learn plenty in school with assignments and lectures I get and with the projects I practice at home. However, of course I have the textbook about C++ from Bjarne Stroustrup, but I only thought about the book having an answer, after I posted here on Stackoverflow. – WolfyDoo Oct 12 '20 at 23:39

1 Answers1

2

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.

cigien
  • 57,834
  • 11
  • 73
  • 112