Based on alk's comment, the approach one can use is sscanf
, like this:
#include <string.h>
int main ()
{
char* str = "15:18:13";
int a, b, c;
sscanf(str, "%d:%d:%d", &a, &b, &c);
printf("%d %d %d\n", a, b, c);
return 0;
}
However, the following is a more general solution.
Use strtok
.
You can store them in an array, like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char str[] ="15:18:13";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,":");
char* a[3];
int i = 0;
while (pch != NULL)
{
a[i] = malloc( (strlen(pch)+1) * sizeof(char));
strcpy(a[i++], pch);
printf ("%s\n",pch);
pch = strtok (NULL, ":");
}
for(i = 0 ; i < 3 ; i++)
printf ("%s\n",a[i]);
return 0;
}
strdup
, as suggested by Deduplicator, can also help, but it is not standard, thus I suggest to avoid (or implement your own, not that hard). :)
Moreover, strtok_s
that Deduplicator mentions is not provided in C.
Reply to OP's comment below:
Question: str is char str[] but time is a char*. Can I convert this?
You can assign it to an array like this:
#include <stdio.h>
int main ()
{
char* from = "15:18:13";
char to[strlen(from) + 1]; // do not forget +1 for the null character!
strcpy(to, from);
printf("%s\n", to);
return 0;
}
GIFT: I suggest you read the first answer from here.
It provides a smooth explanation to char*
and char[]
.