95

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.

sashoalm
  • 75,001
  • 122
  • 434
  • 781
user963241
  • 6,758
  • 19
  • 65
  • 93

11 Answers11

404

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?

Andrew
  • 5,839
  • 1
  • 51
  • 72
Eugene Mayevski 'Callback
  • 45,135
  • 8
  • 71
  • 121
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)

abelenky
  • 63,815
  • 23
  • 109
  • 159
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.)

Nathan S.
  • 5,244
  • 3
  • 45
  • 55
  • 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 Jan 07 '11 at 19:24
  • 2
    @Mark B: Standard C requires that the numbers be consecutive. – Billy ONeal Jan 07 '11 at 20:24
  • @Mark Right, that's definitely safer from a buffer-overflow perspective. – Nathan S. Jan 07 '11 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&0F & code;
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Dorato
  • 81
  • 2
  • 4
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;
}
Matt Ke
  • 3,599
  • 12
  • 30
  • 49
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

Luckabo
  • 74
  • 5
IceSea
  • 101
  • 1
  • 5
2

itoa()

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

Newbie
  • 1,143
  • 5
  • 20
  • 30
  • 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 Jan 07 '11 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. – R.. GitHub STOP HELPING ICE Jan 07 '11 at 19:00
  • "standard" way in C++ would be using streams, all the other methods mentioned so far have some problems. – Gene Bushuyev Jan 07 '11 at 19:46
  • @R..: sorry, could you link the **best** site for c and c++ then ? – Newbie Jan 07 '11 at 21:07
  • For C, http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf - or if you don't mind having some POSIX extensions (clearly marked), http://pubs.opengroup.org/onlinepubs/9699919799/functions/contents.html is a lot more accessible. – R.. GitHub STOP HELPING ICE Jan 07 '11 at 21:20
  • @R..: is there html version from that pdf? – Newbie Jan 08 '11 at 00:42
  • I wish. I've tried using converters but they all seem to do a bad job. Anyone else know where to get a good html copy of the C standard? – R.. GitHub STOP HELPING ICE Jan 08 '11 at 00:43
  • 5
    well, then its inferior compared to cplusplus.com – Newbie Jan 08 '11 at 17:37
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;
cpx
  • 17,009
  • 20
  • 87
  • 142
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.

jun
  • 127
  • 2
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/

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65
-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.