using strtol()

Oct 28, 2015 at 9:50am
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 Oct 28, 2015 at 9:50am
Oct 28, 2015 at 10:12am
The loop condtion is equivalent to while (pa == nullptr). It doesn't look like pa is null or should be null.
Oct 28, 2015 at 10:24am
1
2
3
4
5
6
pa  = a;
pe = nullptr;
do {
    pe = pa;
    nums[j++] = strtol(pa, &pe, 10);
} while(pa != pe);
Oct 28, 2015 at 11:41am
@MiliNiPaa, I don't understand your code
@Peter, what should the loop cond. be then?
Last edited on Oct 28, 2015 at 11:42am
Oct 28, 2015 at 11:55am
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 Oct 28, 2015 at 11:55am
Topic archived. No new replies allowed.