template<class IntType>
IntType atoi_unsafe(const char* source)
{
IntType result = IntType();
while (source)
{
auto t = *source;
result *= 10;
result += (*source - 48);
++source;
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
在main()我有:
char* number = "14256";
atoi_unsafe<unsigned>(number);
Run Code Online (Sandbox Code Playgroud)
但条件while (source)似乎没有认识到source已遍及整个C字符串.它应该如何正确检查字符串的结尾?
Jon*_*ler 11
指针在字符串末尾不会变为零; 当指向的值变为零时,找到字符串的结尾.因此:
while (*source != '\0')
Run Code Online (Sandbox Code Playgroud)
您可以更紧凑地将整个函数编写为:
template<class IntType>
IntType atoi_unsafe(const char* source)
{
IntType result = IntType();
char c;
while ((c = *source++) != '\0')
result = result * 10 + (c - '0');
return result;
}
Run Code Online (Sandbox Code Playgroud)
当然,它不使用auto关键字.还要仔细注意'\0'和之间的区别'0'.循环体中赋值中的括号不是必需的.
你的代码只处理没有符号的字符串 - 并且应该可以证明字符实际上也是数字(如果输入无效则可能引发异常)."不安全"的称谓当然适用.另请注意,如果您为有符号整数类型实例化模板并且值溢出,则会调用未定义的行为.至少对于无符号类型,算术被定义,即使可能不是预期的.