模板函数中的Itoa



代码优先:

template <typename T>
void do_sth(int count)
{
    char str_count[10];
    //...
    itoa(count, str_count, 10);
    //...
}

但是我得到了一些编译错误,像这样:

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

但我确实包括了<cstdlib>。谁能告诉我怎么了?

似乎itoa是一个非标准函数,并不是在所有平台上都可用。请使用snprintf(或类型安全的std::stringstream)。

这是一个非标准函数,通常在stdlib.h中定义(但ANSI-C不保证,参见下面的注释)。

#include<stdlib.h>

则使用itoa()

注意cstdlib没有这个功能。所以包括cstdlib是没有用的。

还要注意这个在线文档说,

<标题> 可移植性

此函数在ANSI-C中没有定义,也不属于C++,但被一些编译器支持。

如果它是在头文件中定义的,那么在c++中,如果你必须使用它作为:

extern "C" 
{
    //avoid name-mangling!
    char *  itoa ( int value, char * str, int base );
}
//then use it
char *output = itoa(/*...params*...*/);

可移植的解决方案

您可以使用sprintf将整数转换为字符串,如:

sprintf(str,"%d",value);// converts to decimal base.
sprintf(str,"%x",value);// converts to hexadecimal base.
sprintf(str,"%o",value);// converts to octal base.

最新更新