char line[255];
char *token = NULL;
char *line2 = NULL;
char *temporaryToken = NULL;
if( scanf(" %[^\n]", line) > 0)
token = strtok( line, ";" ); //divide the line by ;
do
{
line2 = token;
temporaryToken = strtok(line2, " ");
do
{
//divide the line2 by spaces into command and args, not the question here]
temporaryToken = strtok( NULL, " " );
}while (temporaryToken != NULL );
token = strtok( NULL, ";" );
}while(token != NULL);
this is not my code verbatim, by the way, just an example of how it’s set out
In my program, when I print the “token” variable before I split a second time, it’ll print out everything until the ; character.
For example, say stdIn took in “ls -la; mkdir lololol; ls -la”, it would print “ls -la”. But then, after the second split, printing “token” would only print “ls”.
Why is this, and how could I go about fixing it?
There are two problems with
strtok().strtok()calls can be active at a time.I think your problem is the latter. You also have an indentation problem in the code:
You probably intended it to read:
Assuming this is what you intended, you still have the problem that there is one
strtok()running online, and then a second one running online2. The trouble is, the loop online2completely wrecks the interpretation ofline. You can’t use the nested loops withstrtok().If you must use something like
strtok(), then look for either POSIXstrtok_r()or Microsoft’sstrtok_s()(but note that the C11 standard Annex K version ofstrtok_s()is different — see Do you use the TR 24731 ‘safe’ functions?).About the Comments
While you use
strtok()or one of its relatives, the input string will be modified, and if you have multiple delimiters, you will not be able to tell which delimiter was present. You can work with a copy of the string, and do comparisons (usually based on offsets from the start of the string).Within the limits of using
strtok_r(), the solution above ‘works’. Here’s a test program to demonstrate:Example input and output:
Alternative using
strcspn()andstrspn()If you don’t want to demolish the original string, you must use other functions than the
strtok()family. The functionsstrcspn()andstrspn()are suitable; they are part of Standard C (C89 and later versions), albeit much less well known than some of the other functions. But they’re spot on for this task.Example input and output:
This code goes back to the more comfortable
whileloop, rather than needing to usedo-whileloops, which is a benefit.