Home c incorrect translation from int to char

incorrect translation from int to char




A very stupid question, but I can’t get a normal result. You need to convert numbers from the range 10 .. 99 (numbers are stored in int ) to char . As a result, there should be a string of numbers in the given range, which will then be written to a file.

Constructs like:

int a = 65;
char ch = 65;


int a = 65;
char ch = (char) a;

do not work (string contains ASCII characters).
Thanks in advance.

Answer 1, authority 100%

Since you need to translate multi-digit numbers, you simply cannot translate them into char , only into a string (char array).

Since you are working in C, just allocate memory for the string and use sprintf (or safe equivalents):

char s [20]; // For a two-digit, s [3] is enough - don't forget about the null character
sprintf (s, "% d", a);

The itoa option is bad because it is not a standard function.

For specifically two-digit numbers, you can write your own code:

char s [3] = {0}; // To nullify the trailing character
s [0] = '0' + a / 10;
s [1] = '0' + a% 10;

Answer 2

In general, to convert a digit to char, in C they do this:

int a = 8;
char c = a + '0'; // just add the code '0'

There are also special functions in stdlib.h:

# include & lt; stdio.h & gt;
#include & lt; stdlib.h & gt;
void main () {
  char buff [20];
  int a = 12345;
char * p;
  p = itoa (a, buff, 10); // where 10 is the number system

Answer 3

I do not understand the essence of the problem.
I checked – all options worked correctly for me:

int a = 65;
char c = 65;
int a = 65;
char c = a;


a 65 int
c 65 'A' char

Another thing is that if under “It is necessary to convert numbers from the range 10 .. 99 (numbers are stored in int) into char” is understood

1) convert a number to a string,

then you need not char , but at least char [3] , and you can use the itoa function

int a = 57;
char c [3];
itoa (a, (char *) c, 10);

2) converting a number to a digit

but then only 0 to 9 will work, everything else will start producing characters

int a = 3;
char c = '0' + a;

3) converting a digit to a string

but then only 0 to 9 will work

int a = 3;
char c [2];
c [0] = '0' + a;
c [1] = '\ 0';

Better specify exactly where it didn’t work for you.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions