c++ how to convert int to char?

hello if we have int x = 5; and we want to convert x which is == 5 to char so for example char number = x doesnot work i understand why , but how to convert it ? thx
What do you want your char to contain? Symbol with index 5? A symbol '5'? Something else?
symbol '5' also when i ask something like if (number[1]==5) ......
and it will must convert more than one digit numbers for example 10 digit number 284983905 or smth like this
1) '5' and 5 are different. You cannot store both in same variable.
2) Char can store a single symbol. One. So you cannot store several symbols in it.

You might want to consider using std::string to store converted values and std::to_string function to convert them in first place.
aah sorry yea of course i mean to store that in array char , sry i didnot mentioned about it for sure you cant store without using array
If you want to store test representation of some number in a c-string (char array), your best bet would be sprintf():
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdio>


int main()
{
    int i = 213;
    char str[20] = {0};
    std::sprintf(str, "%d", i);
    std::cout << str;
}
213
http://coliru.stacked-crooked.com/a/8c7a48b8744cfb25
Last edited on
thanks ,

and also can i read the char str like if str[1]==2 ....... after converting using this method?
Yes, you can. Result is null terminating character array containing characters representing decimal digits.
and please

std::sprintf(convertto, "%d", convertfrom);
is this right?


i got error

this is 1/100 part of my code



1
2
3
checkpalindrom [10] = {'0'};
   
std::sprintf(checkpalindrom, "%d", convertcheckpalindrom);


and exactly here


{'0'};

error expected and expresion

Last edited on
Technically it is. However I suggest to read on printf function to really understand what is going on.
and how to fix that error look above your post
checkpalindrom [10] = {'0'};
Where is variable type? When you declare something, you need to tell what type your variable is going to be: char checkpalindrom[10]
Why are you filling it with character '0'
aaah sorry dude i made mistake like it was already defined , sorry i know my huge program is nearly done , now how do i convert char to int ?
int x=5;

char(x);
Topic archived. No new replies allowed.