Originally Posted by
laserlight
the solution is to copy the string, then call strtok with the copy.
What is wrong in my code?
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *pos1, *pos2;
char string[256];
printf("Enter a string: ");
fgets(string, 255, stdin);
pos1 = string;
char copy[strlen(string)+1];
strcpy(copy, string);
pos1 = strtok( string, " ,");
while (pos1) {
pos2 = strtok( copy, " ,");
while (pos2) {
printf("pos2 %s\n", pos2); //for debug
if(!strcmp(pos1, pos2) && (string-pos1)<(copy-pos2))
puts(pos2);
pos2 = strtok( NULL, " ,");
}
printf("pos1 %s\n", pos1); //for debug
pos1 = strtok( NULL, " ,");
}
return 0;
}