How can an int be converted to a char

I would like to store an integer to a character array and then display the character (which would be an alpha numeric at that point?). I tried casting to char, but it just changes the integer into some strange character symbol. What can be done?
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;
int main(){
    int a = 10;
    char c;
    c = a+'0';
    cout << c;
    return 0;
}


If you want to change number more than 9 to an array of char,
just loop and do something implemented from this.

btw, you should learn about ASCII code. char '0' = 48 in integer.

try this and see,
1
2
3
4
5
6
7
8
#include <iostream>
using namespace std;
int main(){
	for(int i=0;i<256;i++){
		cout << i << " : " << (char)i << endl;
	}
    return 0;
}
Last edited on
or use c++ stringstream and a string as an alternative to a character array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <sstream>
   
int main()
{
    int n = 1234;
    
    std::ostringstream oss;
    oss << n;
    std::string s = oss.str();
    
    for (size_t i=0; i<s.size(); i++)
    {
        std::cout << s[i] << "  ";
    }
}
1  2  3  4

That is an interesting approach. I was hoping that by now someone had created a function in the C++ library to do all those low-level programming routines based on a few arguments sent to its parameters. As it turns out, I kept surfing the net and found the itoa() function. It functions quite well and seems to be located in #include <cstdlib>.

An example of its use would be:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
#include <cstdlib>
#include <iostream>
using namespace std;

int main()
{
int val =10;
char chaval[3] = {{'A'},{'B'},{'C'}};
cout << chaval << "\n";
itoa(val, chaval, 10);
cout << chaval;
return 0;
}
to_string sounds excellent. However not all compilers (even those which implement some C++11 features) support it. I don't think itoa is a standardised function, so it may not be available.
Last edited on
I'm using VC10, and itoa() comes with it in the <cstdlib>.
Thank you for the two good references (function & website).
@MSH you should know or understand ascii and extended ascii table/code.
and also(optional) thee hexadecimal,decimal and binaries
sprintf()
@dhayden sure he wont understand a single thing if he just use sprintf()
Topic archived. No new replies allowed.