On Sep 26, 1:21*am, Neel <a.k.v...@gmail.com> wrote:
> Hi friends,
> I 'm trying to extract values from a lines which are delimited by a
> space
> eg.
> content of string is: "Hello World"
>
> I use strtok to extract "Hello" and "World"
>
> the code I use is
>
> foo=atoi(strtok(data," "));
> bar=atoi(strtok(NULL," "));
>
> BUT If in case there's only one word, it gives me Segmentation Fault.
> How can I handle this?
> I tried try-catch but didnt work.
From:
http://www.cplusplus.com/reference/c...ng/strtok.html
we have this:
/* strtok example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
The while loop is due to this:
Return Value
A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.