模板函数中的Itoa
itoa in a template function
代码优先:
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.
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 代码在main()中运行,但在函数中出现错误
- 如何将长整型传递给 itoa 函数?
- 最佳base-10仅ITOA()函数
- 'itoa':函数不带1个参数&'c':未声明的标识符
- 模板函数中的Itoa