c - Iterate through string and store numbers in array -


i iterate through string 1.3.6.1.2.1.2.2.1.10.1 , store numbers in array. code works numbers between 0-9 not greater 9 because iterate 1 step , scan number. how can store numbers, not in 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 = 0; < 12; i++)         printf("%d\n", oid_val_arr[i]); } 

should use strtok()?

in code, change this:

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

to this:

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

in order length too. of course need change while loop 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 use strtok() , atoi(), this:

#include <stdio.h> #include <string.h> #include <stdlib.h>  #define size 11  int main () {   int arr[size], = 0;    char str[] ="1.3.6.1.2.1.2.2.1.10.1";   char * pch;   printf ("splitting string \"%s\" tokens:\n",str);   pch = strtok (str,".");   while (pch != null)   {     //printf ("%s\n",pch);     arr[i++] = atoi(pch);     pch = strtok (null, ".");   }   for(i = 0; < size; ++i)       printf("%d ", arr[i]);    printf("\n");   return 0; } 

output:

splitting string "1.3.6.1.2.1.2.2.1.10.1" tokens: 1 3 6 1 2 1 2 2 1 10 1 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -