简体   繁体   中英

How to convert int into a char array?

If I want to compile the following code:

int x = 8;
int y = 17;
char final[2];

final[0] = (char) x;
final[1] = (char) y%10;

cout << final[0] << final[1] << endl;

It shows nothing. I don't know why? So how can I successfully convert it?

(char)8 is not '8' , but the ASCII value 8 (the backspace character). To display the character 8 you can add it to '0' :

int x = 8;
int y = 17;
char final[2];

final[0] = '0' + x;
final[1] = '0' + (y%10);

cout << final[0] << final[1] << endl;

As per your program you are printing char 8, and char 7. They are not printable. In fact they are BELL and Backspace characters respectively. Just run you program and redirect it to a file. Then do an hexdump, you will see what is printed.
./a.out > /tmp/b
hd /tmp/b
00000000 08 07 0a |...|
00000003

What you need to understand is that in C++, chars are numbers , just like ints, only in a smaller range. When you cast the integer 8 to char, C++ thinks you want a char holding the number 8. If we look at our handy ASCII table , we can see that 8 is BS (backspace) and 7 is BEL (which sometimes rings a bell when you print it to a terminal). Neither of those are printable, which is why you aren't seeing anything.

If you just want to print the 87 to standard output, then this code will do that:

cout << x << (y%10) << endl;

If you really need to convert it chars first, then fear not, it can still be done. I'm not much of a C++ person, but this is the way to do it in C:

char final[2];
snprintf(final, sizeof final, "%d%d", x, y % 10);

(See snprintf(3) )

This code treats the 2-char array as a string, and writes the two numbers you specified to it using a printf format string. Strings in C normally end with a NUL byte, and if you extended the array to three chars, the final char would be set to NUL. But because we told snprintf how long the string is, it won't write more chars than it can.

This should also work in C++.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM