How to check if char* p reached end of a C string?
template<class IntType>
IntType atoi_unsafe(const char* source)
{
IntType result = IntType();
while (source)
{
auto t = *source;
result *= 10;
result += (*source - 48);
++source;
}
r开发者_JAVA技巧eturn result;
}
and in main()
I have:
char* number = "14256";
atoi_unsafe<unsigned>(number);
but the condition while (source)
does not seem to recognize that source
has iterated over the entire C string. How should it correctly check for the end of the string?
while(source)
is true until the pointer wraps around to 0, but will probably crash well before that in modern systems. You need to dereference the pointer to find a null byte, while(*source)
.
I hate posting short answers
The pointer does not go to zero at the end of the string; the end of the string is found when the value pointed at becomes zero. Hence:
while (*source != '\0')
You might, more compactly, write the whole function as:
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;
}
Granted, it does not use the auto
keyword. Also note carefully the difference between '\0'
and '0'
. The parentheses in the assignment in the loop body are not necessary.
Your code only handles strings without a sign - and should arguably validate that the characters are actually digits too (maybe raising an exception if the input is invalid). The 'unsafe' appellation certainly applies. Note, too, that if you instantiate the template for a signed integer type and the value overflows, you invoke undefined behaviour. At least with unsigned types, the arithmetic is defined, even if probably not what is expected.
You need to look for the null-terminator at the end of the string. Waiting for the pointer to wrap around to 0
is probably never going to happen. Use while (*source)
for your loop.
精彩评论