Kaushik
Kaushik

Reputation: 53

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

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++
        }

Upvotes: 4

Views: 395

Answers (3)

eerorika
eerorika

Reputation: 238281

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';

Upvotes: 0

Pepijn Kramer
Pepijn Kramer

Reputation: 12849

A safe way is to use std::stoi(), https://en.cppreference.com/w/cpp/string/basic_string/stol

you have all the benefit of using a safe string type (std::string), and stoi will throw exceptions when you have incorrect input.

#include <string>

int main()
{
    std::string txt("123");
    auto value = std::stoi(txt);
}

Also try not to use #include <bits/stdc++.h> https://stackoverflow.com/Questions/31816095/Why-Should-I-Not-Include-Bits-Stdc-H.

Upvotes: -1

iamdhavalparmar
iamdhavalparmar

Reputation: 1218

char c = digit + '0' ;

It will do your work.

Upvotes: 4

Related Questions