1

What I want is the same result as the following program:

int main(){
    char y = '3';
    cout << y;
    return 0;
}

But to first store the int variable into a char array as a char variable. The main body of my program is as follows:

int main(){     
    char x[9];
    int y = 1;  
    x[5] = y;   
    cout << x[5];
    return 0;
}

And there is nothing in the console. I tried also

int main(){
    char x[9];
    int y = 3;
    char m = y;
    x[5] = m;
    cout << m << endl;
    cout << x[5] << endl;
    return 0;
}

But there's still nothing in the console. I looked at other answers and everyone said these two data types can be converted directly, I really wonder where I did wrong and what should I do to get the wanted result.

barbatos233
  • 101
  • 4
  • 6
    What you are missing is that the number 1 is not, I repeat, ***is not***, character "1". That would be number 49. For more information see the Wikipedia article on ASCII. – Sam Varshavchik Apr 09 '21 at 16:10
  • They are converted implicitly, because your code compiles. Try to assign `49` as your char value instead to see `1` in the console. – Yksisarvinen Apr 09 '21 at 16:10
  • Hardcoding 49 will make reading the code hard to read; `int y = '1';` would be better. To demonstrate what the other commenters mentioned you could try this btw: `std::cout << static_cast('1');` – fabian Apr 09 '21 at 16:17
  • Thank you so much! – barbatos233 Apr 09 '21 at 16:17
  • One of the most confusing things when dealing with `std::cout` and, what _clearly_ must be a plain integer, is that a `char` with the value `65` will be displayed as `A` (if we're in ASCII land) and an `int` with the value `65` will be displayed as, well, `65`. There are _a lot_ of `operator<<` overloads. – Ted Lyngmo Apr 09 '21 at 16:24
  • 1
    Try `cout << +x[5];` for more fun. – Aykhan Hagverdili Apr 09 '21 at 16:30

0 Answers0