#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2003
    Posts
    24
    Rep Power
    0

    scanning a char buffer for integers


    Hi,

    Need some help grabbing ints from a buffer.
    I have a function that reads data from a file. the data is just a line of integers separated by spaces. I have this data in a char buffer. I know how many bytes were read into the buffer. What I have to do now, is scan the buffer, reading each integer one by one and performing something on each integer. The number of integers in one file can vary from another file. I want to use sscanf, but don't know how I can read all the integers. THis is my code:

    Code:
    char * buffer;
    int size;
    ...
    /*suppose the buffer has the data now, and size is the size of buffer*/
    
    int numInts=x; 
    /*suppose x is a number that I determined at run-time*/
    int num;
    
    for(int i=0; i<numInts; i++)
    {
       sscanf(buffer, "%i", &num);
      //do something to num
    
    }

    How can I scan the buffer so that the pointer to buffer is actually moving, and not reading the same number in each iteration?

    THanks
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,625
    Rep Power
    4247
    Why not use strstr() and save yourself some work.
    Code:
    #include <string.h>
    char * buffer;
    char tempbuf[30]; 
    char *ptr;
    
    /*suppose x is a number that I determined at run-time*/
    /* Convert the number to a char string -- 
        use sprintf() or itoa() or whatever */
    sprintf(tempbuf, "%d", x);
    
    /* Now look for tempbuf in buffer */
    if ((ptr = strstr(buffer, tempbuf)) != NULL) {
        /* ptr now points to the area in buffer where the number is */
    }
    Hope this helps :)
  4. #3
  5. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,158
    Rep Power
    2222
    Or how's about strtok?
    Code:
    char *sp;
    int *num[numInts];
    
    num = new int[numInts];
    
    sp = strtok(buffer," ");
    
    for(int i=0; i<numInts && sp != NULL; i++)
    {
        num[i] = atoi(sp);
        sp = strtok(NULL," ");
    }

IMN logo majestic logo threadwatch logo seochat tools logo