Why, when one memory subset of a string is passed to a int variable, does printing give me a completely different value?

Viewed 36

I want the first character in string example1 to print out. Using example1[0] seems to work, but for some reason having an int variable have that same value will output 49. Why does this happen, and how can I make the LOG(print) print 1 instead of 49?

#include <iostream>
#include <string>
#define LOG(x) std::cout<<x<<std::endl;
int main() {
    std::string example1 = {"1 2 3 4 5"};
    int print = 0;
    LOG(example1[0]);
    //this prints 1
    print = example1[0];
    LOG(print)
    //this, somehow, prints 49. Why?
}
1 Answers

When you write example1[0], that's a char; if you convert it to an int, it's the ASCII value of it (or, in older/different systems, the value in the specific character table).

Related