assigning an int into a string in C
I need to call a function开发者_如何转开发 which receives a string. I need the string to contain integers. How do I assign the string with the integers?
Thanks, Edo Cohen
You are looking for the snprintf()
function:
http://libslack.org/manpages/snprintf.3.html
Use snprintf
to make the string you need.
try this:
int number = 10;
char mystring[20];
snprintf(mystring, sizeof(mystring), "%d", number);
alternatively you can use itoa
but this is considered unsafe.
use itoa
, or sprintf
as suggested in the link, because of portability reasons.
snprintf
or asprintf
for security reasons..
You could use sprintf to do that:
sprintf(buffer, "%d", 123);
Note that you need to mage sure that your buffer has enough space allocated
i guess this will work
#include <stdlib.h> // for itoa() call
#include <stdio.h> // for printf() call
int main() {
int num = 123;
char buf[5];
// convert 123 to string [buf]
itoa(num, buf, 10);
// print our string
printf("%s\n", buf);
return 0;
}
also u can use--
#include <stdio.h>
int main(void)
{
const char base[] = "filename";
char filename [ FILENAME_MAX ];
int number = 42;
sprintf(filename, "%s%d", base, number);
printf("filename = \"%s\"\n", filename);
return 0;
}
Though remember sprintf() does not calculate for buffer overflow. sprintf() doesn't flush any file buffer, in fact it doesn't have any buffer associated with it. sprintf() operates on a character buffer (not quite the same thing). If you overflow that buffer you can crash the system.
A safer version of sprintf() is snprintf() which unfortunately isn't very standard yet. It appears in various forms from many compiler vendors and was finally standardized in C99 and will hopefully make it as part of standard C++ in the next standard of C++. Until then you just have to dig up the unstandard version of it if you have one.
精彩评论