How to convert an integer to a character in C++

Viewed 83

Say I have an integer and I want to convert it to a character? What methods are available or should I use in C++? For example, refer to the given code below

      #include <bits/stdc++.h>
      using namespace std;
      int main
        {
            int i = 1;
           // Say I want to convert 1 to a char  '1';
           // How do I achieve the following in C++
        }
3 Answers
char c = digit + '0' ;

It will do your work.

You could use an array, which should be easy to understand:

if (i >= 0 && i <= 9) {
    char digits[] = "0123456789";
    char c = digits[i];

Or you can use addition which is slightly trickier to understand. It relies on the (guaranteed) detail that digit symbols are contiguous in the character encoding:

if (i >= 0 && i <= 9) {
    char c = i + '0';
Related