user963241 user963241 - 1 year ago 169
C Question

Convert an int to ASCII character

I have

int i = 6;

and I want

char c = '6'

by conversion. Any simple way to suggest?

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

Answer Source

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

SO way:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download