96

I have

int i = 6;

and I want

char c = '6'

by conversion. Any simple way to suggest?

EDIT: also i need to generate a random number, and convert to a char, then add a '.txt' and access it in an ifstream.

0

11 Answers 11

410

Straightforward way:

char digits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char aChar = digits[i];

Safer way:

char aChar = '0' + i;

Generic way:

itoa(i, ...)

Handy way:

sprintf(myString, "%d", i)

C++ way: (taken from Dave18 answer)

std::ostringstream oss;
oss << 6;

Boss way:

Joe, write me an int to char converter

Studboss way:

char aChar = '6';

Joe's way:

char aChar = '6'; //int i = 6;

Nasa's way:

//Waiting for reply from satellite...

Alien's way: '9'

//Greetings.

God's way:

Bruh I built this

Peter Pan's way:

char aChar;

switch (i)
{
  case 0:
    aChar = '0';
    break;
  case 1:
    aChar = '1';
    break;
  case 2:
    aChar = '2';
    break;
  case 3:
    aChar = '3';
    break;
  case 4:
    aChar = '4';
    break;
  case 5:
    aChar = '5';
    break;
  case 6:
    aChar = '6';
    break;
  case 7:
    aChar = '7';
    break;
  case 8:
    aChar = '8';
    break;
  case 9:
    aChar = '9';
    break;
  default:
    aChar = '?';
    break;
}

Santa Claus's way:

//Wait till Christmas!
sleep(457347347);

Gravity's way:

//What

'6' (Jersey) Mikes'™ way:

//

SO way:

Guys, how do I avoid reading beginner's guide to C++?

My way:

or the highway.

Comment: I've added Handy way and C++ way (to have a complete collection) and I'm saving this as a wiki.

Edit: satisfied?

13
  • 16
    You meant "boss" as in superior, but I read it as in "boss", as in "Bruce Springsteen is the boss." Maybe you could revise for that case?
    – user67416
    Commented May 1, 2013 at 18:10
  • 8
    About about Joe's way? Or Nasa's way? or Aliens way? Or Gods way? Or Peter Pans way? How about Santa Claus's way? Or Gravity's way? You should start a list? Maybe check it twice just in case you missed something? Commented Jun 26, 2016 at 22:01
  • 2
    @AbstractDissonance can a get that with Mikes Way™ ... I like me some Jersey Mikes.
    – cb88
    Commented Aug 1, 2016 at 20:01
  • 1
    This made me laugh so hard.
    – NateW
    Commented Sep 19, 2018 at 17:40
  • 1
    This has to be the best answer on SO xD
    – Seth
    Commented Jun 10, 2020 at 3:10
37

This will only work for int-digits 0-9, but your question seems to suggest that might be enough.

It works by adding the ASCII value of char '0' to the integer digit.

int i=6;
char c = '0'+i;  // now c is '6'

For example:

'0'+0 = '0'
'0'+1 = '1'
'0'+2 = '2'
'0'+3 = '3'

Edit

It is unclear what you mean, "work for alphabets"? If you want the 5th letter of the alphabet:

int i=5;
char c = 'A'-1 + i; // c is now 'E', the 5th letter.

Note that because in C/Ascii, A is considered the 0th letter of the alphabet, I do a minus-1 to compensate for the normally understood meaning of 5th letter.

Adjust as appropriate for your specific situation.
(and test-test-test! any code you write)

2
  • Confusing when choosing between small and capital letters.
    – user963241
    Commented Jan 7, 2011 at 19:00
  • 4
    Well, you need to tell us what you want. "Work for alphabets" really isn't very descriptive.
    – EboMike
    Commented Jan 7, 2011 at 19:06
16

Just FYI, if you want more than single digit numbers you can use sprintf:

char txt[16];
int myNum = 20;
sprintf(txt, "%d", myNum);

Then the first digit is in a char at txt[0], and so on.

(This is the C approach, not the C++ approach. The C++ way would be to use stringstreams.)

3
  • 3
    Always prefer snprintf over sprintf (consider a hypothetical system with 128 bit ints or whatever). +1 anyway for an approach that won't break in character sets where the numbers aren't consecutive.
    – Mark B
    Commented Jan 7, 2011 at 19:24
  • 2
    @Mark B: Standard C requires that the numbers be consecutive. Commented Jan 7, 2011 at 20:24
  • @Mark Right, that's definitely safer from a buffer-overflow perspective.
    – Nathan S.
    Commented Jan 7, 2011 at 21:04
5

This is how I converted a number to an ASCII code
0 though 9 in hex code is 0x30 - 0x39
6 would be 0x36

unsigned int temp = 6;
// or you can use 'unsigned char temp = 6;
unsigned char num;
num = 0x30 | temp;

This will give you the ASCII value for 6. You do the same for 0 - 9

To convert ASCII to a numeric value I came up with this code

unsigned char num, code;
code = 0x39; // ASCII Code for 9 in Hex
num = 0 & 0 F & code;
4

My way to do this job is:

char to int
char var;
cout<<(int)var-48;
    
int to char
int var;
cout<<(char)(var|48);

And I write these functions for conversions:

int char2int(char *szBroj){
    int counter=0;
    int results=0;
    while(1){
        if(szBroj[counter]=='\0'){
            break;
        }else{
            results*=10;
            results+=(int)szBroj[counter]-48;
            counter++;
        }
    }
    return results;
}

char * int2char(int iNumber){
    int iNumbersCount=0;
    int iTmpNum=iNumber;
    while(iTmpNum){
        iTmpNum/=10;
        iNumbersCount++;
    }
    char *buffer=new char[iNumbersCount+1];
    for(int i=iNumbersCount-1;i>=0;i--){
        buffer[i]=(char)((iNumber%10)|48);
        iNumber/=10;
    }
    buffer[iNumbersCount]='\0';
    return buffer;
}
2

itoa()

http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

8
  • I like this approach better than the character arithmetic suggested by abelenky because it doesn't depend on working with the ASCII character set (even though that is a fairly safe assumption for many applications). However, itoa stores its result in a string, so you need to provide a character array and extract the character from it. Your answer would be more helpful to neophytes if you edited it to show those extra steps.
    – A. Levy
    Commented Jan 7, 2011 at 18:56
  • 5
    -1 both for itoa (nonstandard MS function) and for linking to perhaps the worst site for C and C++ [mis]information. Commented Jan 7, 2011 at 19:00
  • "standard" way in C++ would be using streams, all the other methods mentioned so far have some problems. Commented Jan 7, 2011 at 19:46
  • @R..: sorry, could you link the best site for c and c++ then ?
    – Newbie
    Commented Jan 7, 2011 at 21:07
  • 5
    well, then its inferior compared to cplusplus.com
    – Newbie
    Commented Jan 8, 2011 at 17:37
2

I suppose that

std::to_string(i)

could do the job, it's an overloaded function, it could be any numeric type such as int, double or float

1
  • 2
    for example, char c = to_string(9)[0];
    – IceSea
    Commented Apr 1, 2017 at 5:42
0

"I have int i = 6; and I want char c = '6' by conversion. Any simple way to suggest?"

There are only 10 numbers. So write a function that takes an int from 0-9 and returns the ascii code. Just look it up in an ascii table and write a function with ifs or a select case.

0

Alternative way, But non-standard.

int i = 6;
char c[2];
char *str = NULL;
if (_itoa_s(i, c, 2, 10) == 0)
   str = c;

Or Using standard c++ stringstream

 std::ostringstream oss;
 oss << 6;
3
  • itoa is non-standard and unsafe (could cause buffer overrun).
    – EboMike
    Commented Jan 7, 2011 at 19:07
  • Okay, you're edited it to the _s version now. Still non-standard, but I removed my downvote!
    – EboMike
    Commented Jan 7, 2011 at 19:15
  • Right! I'm mistyped the object name which should be 'oss' :)
    – cpx
    Commented Jan 7, 2011 at 21:41
0

Doing college work I gathered the data I found and gave me this result:

"The input consists of a single line with multiple integers, separated by a blank space. The end of the entry is identified by the number -1, which should not be processed."

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    char numeros[100]; //vetor para armazenar a entrada dos numeros a serem convertidos
    int count = 0, soma = 0;

    cin.getline(numeros, 100);

    system("cls"); // limpa a tela

    for(int i = 0; i < 100; i++)
    {
        if (numeros[i] == '-') // condicao de existencia do for
            i = 100;
        else
        {
            if(numeros[i] == ' ') // condicao que ao encontrar um espaco manda o resultado dos dados lidos e zera a contagem
            {
                if(count == 2) // se contegem for 2 divide por 10 por nao ter casa da centena
                    soma = soma / 10;
                if(count == 1) // se contagem for 1 divide por 100 por nao ter casa da dezena
                    soma = soma / 100;


                cout << (char)soma; // saida das letras do codigo ascii
                count = 0;

            }
            else
            {
                count ++; // contagem aumenta para saber se o numero esta na centena/dezena ou unitaria
                if(count == 1)
                    soma =  ('0' - numeros[i]) * -100; // a ideia é que o resultado de '0' - 'x' = -x (um numero inteiro)
                if(count == 2)
                    soma = soma + ('0' - numeros[i]) * -10; // todos multiplicam por -1 para retornar um valor positivo
                if(count == 3)
                    soma = soma + ('0' - numeros[i]) * -1; /* caso pense em entrada de valores na casa do milhar, deve-se alterar esses 3 if´s
        alem de adicionar mais um para a casa do milhar. */
            }
        }
    }

    return 0;
}

The comments are in Portuguese but I think you should understand. Any questions send me a message on linkedin: https://www.linkedin.com/in/marcosfreitasds/

1
  • 1
    It would be really great if you, or somebody else of course, could translate the comments!
    – csabinho
    Commented Nov 14, 2019 at 19:17
-4
          A PROGRAM TO CONVERT INT INTO ASCII.




          #include<stdio.h>
          #include<string.h>
          #include<conio.h>

           char data[1000]= {' '};           /*thing in the bracket is optional*/
           char data1[1000]={' '};
           int val, a;
           char varray [9];

           void binary (int digit)
          {
              if(digit==0)
               val=48;
              if(digit==1)
               val=49;
              if(digit==2)
               val=50;
              if(digit==3)
               val=51;
              if(digit==4)
               val=52;
              if(digit==5)
               val=53;
              if(digit==6)
               val=54;
              if(digit==7)
               val=55;
              if(digit==8)
               val=56;
              if(digit==9)
                val=57;
                a=0;

           while(val!=0)
           {
              if(val%2==0)
               {
                varray[a]= '0';
               }

               else
               varray[a]='1';
               val=val/2;
               a++;
           }


           while(a!=7)
          {
            varray[a]='0';
            a++;
           }


          varray [8] = NULL;
          strrev (varray);
          strcpy (data1,varray);
          strcat (data1,data);
          strcpy (data,data1);

         }


          void main()
         {
           int num;
           clrscr();
           printf("enter number\n");
           scanf("%d",&num);
           if(num==0)
           binary(0);
           else
           while(num>0)
           {
           binary(num%10);
           num=num/10;
           }
           puts(data);
           getch();

           }

I check my coding and its working good.let me know if its helpful.thanks.

1
  • 1
    you could work on your indentation... and think a lot about other problems in that code.
    – harper
    Commented May 31, 2013 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.