Hello i need help using sscanf to parse commands entered by the user.
The function sscanf() can be used to parse the command lines entered by the user. Suppose the user has entered a command at the keyboard and you have stored it in a character array called command. Suppose also that there are two character arrays called cmd1 and cmd2. To copy the first word out of command into cmd1 use this command:
sscanf(command, "%s", cmd1);
You can now test cmd1 using strcmp() to determine what the command is. If it is a command for which there is a second word (example: GO) then you can read both words using this command:
sscanf(command, "%s %s", cmd1, cmd2);
Now you can check cmd2 to determine the rest of the command which must then be executed. Note: You cannot assume that every command will have two words. The QUIT command is only one word. You will get an error if you try to read the one-word command using sscanf(command, "%s %s", cmd1, cmd2);
The first commands are GO, FIGHT, TAKE, QUIT
if the user enters GO the seconds words are NORTH, SOUTH, EAST, WEST, UP, DOWN
I think you should forget character array, sscanf and other old C string functions unless it's homework and you have to use it.
In C++ you can use a string and stringstream
While I agree with regard to avoiding scanf() or its variations, and using c++ features instead, there is a particular logic implied in the original question.
1. read cmd1 from command
2. test cmd1 has the value "GO"
if yes, start again and read both cmd1 and cmd2 from command
In fact, the amount of detail given suggests that sscanf(), strcmp() and character arrays must be used - which is the C approach, but it may be necessary to satisfy requirements of the assignment.
void processCommand(char *command)
{
char cmd1[255];
char cmd2[255];
int numWords = sscanf(command,"%s %s",cmd1,cmd2);
switch (numWords)
{
case 0:
printf("no words found");
break;
case 1:
printf ("found a single word '%s'",cmd1);
// now search an array of [FIGHT, TAKE, QUIT] to see if its a valid single word
break;
case 2:
printf ("found two words '%s' and '%s'",cmd1, cmd2);
// only GO supports a second word
if (0!=strcmp("GO",cmd1))
{
printf("bad command, only GO has a second word");
}
else
{
// now search an array of [NORTH, SOUTH, EAST, WEST, UP, DOWN] to see if cmd2 is valid
}
break;
}
}