#include<iostream>
#include<cstring>
using namespace std;
char *mystrtok(char str[],char delim)
{
//string and single char acts as delimiter
static char *input =NULL;
if (str!=NULL)
{
//we are making a first call
input=str;
}
//check here base case after final token has been returned
if (input==NULL)
{
return NULL;
}
//start extracting tokens and store them in a array
char *output=new char[strlen(input)+1];
int i=0;
for (i; input[i]!='\0' ; i++)
{
if (input[i]!=delim)
{
output[i]=input[i];
}
else
{
output[i]='\0';
input=input+i+1;
return output;
}
}
output[i]='\0';
input=NULL;
return output;
}
int main(){
char a[100]="Today, is a rainy, day";
char *ptr=mystrtok(a,' ');
cout<<ptr<<endl;
while (ptr!=NULL)
{
ptr=mystrtok(NULL,' ');
cout<<ptr<<endl;
}
return 0;
}
My code is giving segmentation fault in my machine
hello @sagar_aggarwal

first print cout<<ptr;
and then call mystrtok.
reason -> value return by mystrtok can be NULL
then first word would be printed twice?
remove that first cout that u have write before while loop
thanks got your point
i m not much active on whatsapp.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.