Sam Sam - 1 month ago 12
C Question

Iterate through string and store numbers in array

I like to iterate through the string

1.3.6.1.2.1.2.2.1.10.1
and store all numbers in a array. My code works for numbers between
0-9
but not for greater than
9
because I iterate just one step and scan the number. How can I store all numbers, not like in my current output :
1 3 6 1 2 1 2 2 1 10 0 1
(without linebreak)?

int main(int argc, char *argv[])
{
//char * string = "1.3.6.1.2.1.2.2.1.9.1"; /* OK */
char * string = "1.3.6.1.2.1.2.2.1.10.1"; /* NOK */
static int oid_val_arr[256];
char *oid_tmp = string;
int idx = 0;
while (*oid_tmp)
{
int number;
if (sscanf(oid_tmp, "%d", &number) == 1)
{
oid_val_arr[idx] = number;
idx++;
}
oid_tmp++; /* PROBLEM */
}

for(int i = 0; i < 12; i++)
printf("%d\n", oid_val_arr[i]);
}


Should I use strtok()?

Answer Source

In your code, change this:

if(sscanf(oid_tmp, "%d", &number) == 1)

to this:

if(sscanf(oid_tmp, "%d%n", &number, &len) == 1)

in order to get the length too. Then of course you would need to change your while loop like this:

while (*oid_tmp)
{
    int number;
    int len;
    if(sscanf(oid_tmp, "%d%n", &number, &len) == 1)
    {
        oid_val_arr[idx++] = number;
        oid_tmp += len;
    }
    else
    {
        ++oid_tmp;
    }
}

as BLUEPIXY said.


Another approach would be to use strtok() and atoi(), like this:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 11

int main ()
{
  int arr[SIZE], i = 0; 
  char str[] ="1.3.6.1.2.1.2.2.1.10.1";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str,".");
  while (pch != NULL)
  {
    //printf ("%s\n",pch);
    arr[i++] = atoi(pch);
    pch = strtok (NULL, ".");
  }
  for(i = 0; i < SIZE; ++i)
      printf("%d ", arr[i]);
   printf("\n");
  return 0;
}

Output:

Splitting string "1.3.6.1.2.1.2.2.1.10.1" into tokens:
1 3 6 1 2 1 2 2 1 10 1