I was writing a code where i will ask a user for a command input, then i have to sperate the string into substring using " " (space) as delimiter. below is my code...
//some code above...
printf("\nEnter command: ");
fgets(comd, 20, stdin);
printf("\nrecived: %s\n", comd);
comd[strlen(comd)-1] = '\0'; //putting null at the end instead of "\n"
//scanf("\n%[^\n]%*c", comd);
if(strcmp(comd, "exit") != 0 && strcmp(comd, "EXIT") != 0)
{
int i = 1, arg = (strocc(comd, ' ')); //strocc() returns total occurance of the char passed...
char* rest = comd, args[arg+1][15], *tok;
tok = strtok_r(comd, " ", &rest);
strncpy(args[0], tok, strlen(tok));
printf("\ncommand: %s Arguments: %s Total arguments: %d\n", args[0], rest, arg);
while(i < arg+1)
{
strcpy(comd, rest);
tok = strtok_r(comd, " ", &rest);
strncpy(args[i], tok, strlen(tok));
printf("%s, (%d)\n", args[i], i); //printing all arguments one by one...
i++;
}
//some more code...
}
but after tokenizing my origional string there is most of the time some grabage in the tokened string i.e.
//output
Enter command: ./q3 ./q2 23
recieved: ./q3 ./q2 23
//printed tokenized string
command: ./q3� Arguments: ./q2 23 Total arguments: 2
./q2, (1)
23I?t�, (2)
i tried assigning my string 'tok and args[]' to null before puting char init but it didn't worked