4

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++
        }
Kaushik
  • 53
  • 4
  • Just do `1 + '0'`. – mediocrevegetable1 Aug 21 '21 at 17:49
  • `char c = '0' + i;` – Eljay Aug 21 '21 at 17:50
  • 1
    Why the `rcpp` tag? And [never include ``](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h). Also, for simple examples it might be oaky, but otherwise `using namespace std;` is [a bad habit](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). – Some programmer dude Aug 21 '21 at 17:52
  • As for your problem, the C++ specification states that all digits must be contiguously encoded. That is, `'2'` must be exactly one larger than `'1'` which must in turn be exactly one larger than `'0'`. From that it can be deduced that plain arithmetic (addition and subtraction) can be used to go from a digit to its corresponding character, or the opposite. – Some programmer dude Aug 21 '21 at 17:54
  • By the way, the "contiguousnes" of digits is only specified for digits. It can't reliably or portably be used for anything else. – Some programmer dude Aug 21 '21 at 17:58
  • Concur with @Someprogrammerdude and will remove the `rcpp` tag. There are also ... FAQ documents for C++ that are worth perusing. – Dirk Eddelbuettel Aug 21 '21 at 18:12

3 Answers3

4
char c = digit + '0' ;

It will do your work.

iamdhavalparmar
  • 1,090
  • 6
  • 23
0

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';
eerorika
  • 232,697
  • 12
  • 197
  • 326
-1

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.

Pepijn Kramer
  • 9,356
  • 2
  • 8
  • 19