문제

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 declared 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.
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top