using strtol()

Hi.
What's wrong
1
2
3
4
5
6
7
8
pa  = a;
    
    while(!pa)  
   {
       nums[j] = strtol(pa, &pa, 10);
    
       ++j;
   }
Last edited on
The loop condtion is equivalent to while (pa == nullptr). It doesn't look like pa is null or should be null.
1
2
3
4
5
6
pa  = a;
pe = nullptr;
do {
    pe = pa;
    nums[j++] = strtol(pa, &pe, 10);
} while(pa != pe);
@MiliNiPaa, I don't understand your code
@Peter, what should the loop cond. be then?
Last edited on
what should the loop cond. be then?
cppreference wrote:
If the str is empty or does not have the expected form, no conversion is performed, and (if str_end is not NULL) the value of str is stored in the object pointed to by str_end.
http://en.cppreference.com/w/cpp/string/byte/strtol
You can see that when conversion cannot be done, strtol sets second parameter to be same as first. You should check that. Obviously to do that first and second parameters should be different variables.

I don't understand your code
There is a bug in it, disregard it. This is correct code:
1
2
3
4
5
6
char* pa  = a;
char* pend = pa; //Pointer to the end of parsed data
do {
    pa = pend; //Start converting from place where we finished last time
    nums[j++] = strtol(pa, &pend, 10); //Try to do the conversion
} while(pa != pend); //If conversion fails, pa will be equal to the pend, ending the loop 
Last edited on
Topic archived. No new replies allowed.