-1

I'm trying to convert an integer to a string in C but the current code doesn't make it.

I'm not seeking to display it in the screen, so all the functions printf, sprintf... are irrelevant.

int X = 15;
char *T;    
T = (char*)X;
// Expected result : "15"

Can anyone help please ?

Thanks.

Thomas Carlton
  • 5,344
  • 10
  • 63
  • 126
  • (s)tring(printf). e.g. print to a string in memory. just because it says "print" doesn't mean it's going to show up on your screen (or printer, for that matter). – Marc B May 11 '15 at 20:52

2 Answers2

3

Not displaying it to screen doesn't invalidate functions like sprintf() since they literally "print to string".

int X = 15;
char buffer[10];
memset(&buffer, 0, sizeof(buffer)); // zero out the buffer    
sprintf(buffer, "%d", X);
// Expected result : "15"
printf("contents of buffer: %s\n", buffer);
rost0031
  • 1,894
  • 12
  • 21
2

sprintf will print to a string, not the screen.

It's exactly what you're looking for.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Funny enough, `itoa` and all of its variations even go so far as omitting the entire `print` part as well as losing that last `f` -- since you don't need a lot of "formatting" for a simple int-to-string. – Jongware May 11 '15 at 21:11