-
strcmp question
Part of my file:
Code:
int main(void)
{
int done = 0;
char line[300];
do
{
printf("> ");
fgets(line, 300, stdin);
line[strlen(line) - 1] = '\0';
if(strcmp(line, "area items") == 0)
{
areaItems(current, startPtr);
}
if(strcmp(line, "commands") == 0)
{
commands();
}
//...etc
}while(! done);
return(0);
}
The code is working fine. However, I'd like the user to be able to type "grab butter" or "grab toast" or "grab [item]". Can I still use strcmp to read in grab but store the second word in a char name[10]? Or is there something much better to use than strcmp?
Hope that makes sense. Thanks
-
You can use strtok to parse any command the user enters into a series of tokens. Then you can use strcmp on the first token to see if it's "grab", and then do whatever you want with the remaining tokens.
-
sscanf will do what you want.
Quzah.
-
As quzah suggested, you would want an fgets / sscanf pair; which is the easiest way, IMO, to get user input. So something like this:
Code:
#include <stdio.h>
int main(void){
char inputBuffer[100]={0};
char word1[10]={0}, word2[10]={0};
printf("> ");
//grab entire lineof input
fgets(inputBuffer, sizeof(inputBuffer), stdin);
//Parse the line into, in this case 2 different strings seperated by spaces
//it could be any format you want, e.g. %s %d %s %c, ect.
sscanf(inputBuffer, "%s %s", word1, word2);
printf("Word1:%s Word2:%s ", word1, word2);
getchar();
return (0);
}
-
Thanks! Got sscanf to work
-
If you only care if the words are present... but arent worried about the order... you could use strstr() which might be faster...