itoa in a template function
Code goes first:
template <typename T>
void do_sth(int count)
{
char str_count[10];
//...
itoa(count, str_count, 10);
//...
}
but I got some compile-error like this:
error: there are no arguments to ‘itoa’ that depend on a template parameter, so a declaration of ‘itoa’ must be available
error: ‘itoa’ was not dec开发者_如何学JAVAlared in this scope
But I indeed included <cstdlib>
.
Who can tell me what's wrong?
It appears that itoa is a non-standard function and not available on all platforms. Use snprintf instead (or type-safe std::stringstream).
It is a non-standard function, usually defined in stdlib.h
(but it is not gauranteed by ANSI-C, see the note below).
#include<stdlib.h>
then use itoa()
Note that cstdlib
doesn't have this function. So including cstdlib
wouldn't help.
Also note that this online doc says,
Portability
This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
If it's defined in the header, then in C++, if you've to use it as:
extern "C"
{
//avoid name-mangling!
char * itoa ( int value, char * str, int base );
}
//then use it
char *output = itoa(/*...params*...*/);
A portable solution
You can use sprintf
to convert the integer into string as:
sprintf(str,"%d",value);// converts to decimal base.
sprintf(str,"%x",value);// converts to hexadecimal base.
sprintf(str,"%o",value);// converts to octal base.
精彩评论