c - Separating a string into smaller strings -


i have following string abcd1234 , want find way break string 2 different strings, abcd , 1234. have tried following code:

char buf[100],*str1,*str2; int x; fgets(buf,sizeof(buf),stdin); str1=strtok(buf,"0123456789 \t\n"); str2=strtok(null," \n\t\0"); puts(str1); puts(str2); x=atoi(str2); printf("x=%d", x); 

but output abcd 234. , if try 1 letter , 1 number, e.g a2 take e on output , x 0.

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>  size_t extract(const char **sp, char *out, int (*test)(int ch));  int main(void){     char buf[100], str1[100], str2[100];     int x;     const char *p = buf;     //size_t len;      fgets(buf, sizeof(buf), stdin);     while(*p){         if(isalpha((unsigned char)*p)){             extract(&p, str1, isalpha);             puts(str1);         } else if(isdigit((unsigned char)*p)){             extract(&p, str2, isdigit);             x = atoi(str2);             printf("%s, x=%d\n", str2, x);         } else {             ++p;//skip 1 char         }     }     return 0; }  size_t extract(const char **sp, char *out, int (*test)(int ch)){     const char *p = *sp;     while(*p && test((unsigned char)*p)){         *out++ = *p++;     }     *out = '\0';     size_t len = p - *sp;     *sp = p;     return len; } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -