Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert integer into an array

Tags:

c

I am working on a C program, and I am coming across a small problem. I don't know how to convert an integer (say 2007) into a char array. Is there a function in the C libraries to do that for me?

To clarify, I'd like to take 2007 and store it in some char array[4] ={ '2', '0', '0', '7', '\0' };

I was thinking something like sprintf, but I'm not sure. Anyways, any help/hints would be appreciated.

Thanks, Michael

like image 259
Micky Avatar asked May 18 '26 12:05

Micky


1 Answers

You can do that with sprintf, or more safely snprintf.

Here's a contrived example:

#include <stdio.h>
#define MAX_LEN 5

char str[MAX_LEN];
snprintf(str, MAX_LEN, "%d", 2007);
like image 125
Todd Gamblin Avatar answered May 21 '26 02:05

Todd Gamblin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!