Home > Mobile >  Comparing strings using strtock with parsed input
Comparing strings using strtock with parsed input

Time:11-13

I am taking input and then parsing the string word by word, but I need to identify the type of each word and therefore need to be able to directly compare the first word of the string in input to one of my predefined commands.

My issue is that the input consists of a command and then its parameters so I have to parse through STDIN word by word but when I use strcmp it doesn't work unless I remove the parameters or include a space in my strcmp.

My code is below:

#include <string.h>
#include <stdio.h>

int main () {
   char input[100];
   printf("Enter your input: ");
   fgets(input, 100, stdin);
   printf("Reading input... \n");
   const char s[2] = " ";
   char *arg;
   
   /* get the first token */
   arg = strtok(input, s);
   printf("First word: %s\n", arg);
   if(strcmp(arg, "ATTACK")){
       printf("Input Match\n");
   }
   
   return(0);
}

For instance, if I give the input of "ATTACK 50 40" it will not give me an Input Match despite the first word being ATTACK.

I tried checking what was being stored in my arg variable to ensure that strcmp was comparing the right thing and it seemingly was but I realized it was possible it was including the whitespace between the command and the parameters.

I tried adding a space in the strcmp's "ATTACK" so it became "ATTACK " and it worked but I was wondering if there is a way I can have a garbage collecting variable which will remove the whitespace from the variable or if I can specify to remove the last character if it is whitespace.

CodePudding user response:

strcmp returns 0 if the strings are equal

do

if(strcmp(arg, "ATTACK") == 0){
  • Related