Search code examples
cstrtolstrchr

reading in a variable number of long ints on one line using strchr and strtol


My function is not quite done yet, but what I'm going to do is:

  • To read in a string of numbers separated by spaces.
  • Extract the numbers from that string.
  • Convert them to long ints.
  • Return the number of numbers read in.

    int input( int a, int b, long int *result_array )
    {
        int ele = 0;
        char buffer[200];
        char *start, *end;
    
        scanf("%[^\n]%*c", buffer );
    
        start = buffer;
    
        while( ( end = ( strchr( start, ' ' ) ) != NULL ) )
        {
            result_array = strtol( start, &end, 10 );
            ele += 1;
            start = end + 1;
    
    
        }
    
        return ele;
    }
    

It doesn't seem to work properly, I think I'm using strchr wrong.


Solution

  • strtol() returns:

    On success, the function returns the converted integral number as a long int value. If no valid conversion could be performed, a zero value is returned (0L).

    you should re write your code as:

    end = buffer;
    base = 10;
    long int = li;
    ele = 0;
    while(li=strtol (end,&end, base)){
         ele += 1;
    }
    return ele;
    

    You don't need to explicitly use strstr() to locate for next integer. strtol() smart enough and after each conversion it locate end point to next int.

    I have written an running code may be your find helpful:

    #include <stdio.h>      /* printf */
    #include <stdlib.h>     /* strtol */
    int main (){
      char buffer[] = "2001 11 223   444   566";
      char * end;
      long int li;
      end =buffer;
      int base =10;
      int ele = 0;
      while(li=strtol (end, &end, base)){
         printf("%ld \n", li);
         ele += 1;
      }
      printf("\nNo of elements: %d", ele);
      return 0;
    }
    

    its output:

    2001 
    11 
    223 
    444 
    566 
    
    No of elements: 5
    

    Link to codepad