c - substring of a string and print it out -
c - substring of a string and print it out -
i want disect next string:
char msg[30] ="hello 13 1"; char *psh; int num1; int num2; char s[30],s[30];
i seek but:
pch = strtok (msg," "); while (pch != null) { printf ("%s\n",pch); pch = strtok (null, " "); }
which outputs:
hello 13 1
i want create number '13' equal num1, number '1' equal num2:
printf("%d\n",num1); output: 13 printf("%d\n",num2); output: 1
i try:
sscanf(sc, "%s %d %d", &s, &num1, &num2);
which outputs:
segmentation fault
thanks
[edit]
char * pch char s[30]; char sc[30]; char num1[30]; char num2[30]; pch = strtok (s," "); while (pch != null) { printf ("%s\n",pch); pch = strtok (null, " "); } sscanf(sc, "%s %d %d", pch, &num1, &num2);
use sscanf function:
sscanf(msg, "%s %d %d", s, &num1, &num2);
which result in code looking this:
#include <stdio.h> int main() { char msg[30] = "hello 13 1"; int num1, num2; char s[30]; sscanf(msg, "%s %d %d", s, &num1, &num2); printf("%d\n%d\n", num1, num2); homecoming 0; }
c string substring strtok strncpy
Comments
Post a Comment