To read the second string, you need to pass NULL
to strtok()
. Keep in mind that fgets()
retains the newline character from the input line, so you should change your delimiter definition from char s[2] = " ";
to char s[] = " \r\n";
, or char s* = " \r\n"
. This way the second token will not include any newline characters. Also note that strtok()
returns a NULL
pointer if no token is found, so the below code tests for this before printing the read tokens.
But, since you say that there are only two strings, I would consider just using sscanf()
for this. Using the %s
conversion specifier, sscanf()
will read characters into a string until a whitespace character is encountered, but will not include this whitespace character in the string. When you use the %s
specifier in a scanf()
type function, you should specify a maximum field width to avoid buffer overflow. This maximum width should be one less than the size of the buffer to leave room for the '\0'
string terminator, 255 in this case. The sscanf()
function returns the number of successful assignments made, which should be 2 in this case. The sscanf()
approach shown below (commented out) checks this return value before printing the strings.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_MAX 256
int main(void) {
char command[BUFFER_MAX];
char *token1 = NULL;
char *token2 = NULL;
const char *s = " \r\n";
fprintf(stdout, "$ Please enter a command \n");
fflush( stdout );
fgets ( command, BUFFER_MAX, stdin );
token1 = strtok(command, s);
token2 = strtok(NULL, s);
if (token1 && token2 && strcmp(token1, "loaddungeon") == 0) {
fprintf(stdout, "$ loaded successfully: %s\n", token2);
fflush( stdout );
}
/* or instead do this */
/*
char word1[BUFFER_MAX], word2[BUFFER_MAX];
if (sscanf(command, "%255s %255s", word1, word2) == 2) {
if (strcmp(word1, "loaddungeon") == 0){
fprintf(stdout, "$ loaded successfully: %s\n", word2);
fflush( stdout );
}
}
*/
return 0;
}