How to check if char * p has reached the end of line C?

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; } 

and in main() I have:

 char* number = "14256"; atoi_unsafe<unsigned>(number); 

but the while (source) condition does not seem to recognize that source has iterated over the entire string C. How to check the end of the string correctly?

+4
source share
3 answers

while(source) true until the pointer breaks to 0, but most likely will work long before that on modern systems. You need to dereference the pointer to find the null byte, while(*source) .

I hate posting short answers

+12
source

The pointer does not end at the end of the line; end of line is found when the specified value becomes zero. Hence:

 while (*source != '\0') 

You can, more compactly, write the entire function as follows:

 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; } 

Of course, it does not use the auto keyword. Also note the difference between '\0' and '0' . Brackets in assignment in the loop body are not needed.

Your code only processes unsigned strings - and perhaps confirms that the characters are actually numbers (perhaps throwing an exception if the input is invalid). An “unsafe” appeal certainly applies. Note also that if you instantiate a template for a signed integer type and overflow the value, you invoke undefined behavior. At least with unsigned types, arithmetic is defined, even if probably not what is expected.

+11
source

You need to search for a null terminator at the end of the line. Waiting for the pointer to wrap around 0 will probably never happen. Use while (*source) for your loop.

+3
source

All Articles