VanLighto
VanLighto

Reputation: 21

Can't get my code to enter the if else statements

printf("Please enter a command or input file press !commands for more info.\n");

char command[20];

//fgets(command, 20, stdin);
scanf("%s", &command);

printf("%s\n", command);

    while(!strcmp(command, "kill")){

        if (!strcmp(command, "script")){

            printf("testing script\n");

            break;
        }

        else if(!strcmp(command, "test")){
            printf("testing\n");
            break;
        }

        else if(!strcmp(command, "quit")){
            char yesorno;

            printf("Do you really want to quit? Y/N\n");
            scanf(" %c", &yesorno);
                if (yesorno == 'Y'){
                    exit(0);

                }
                else if (yesorno == 'N'){
                    break;
                }
                else{
                    printf("You did not enter Y or N!\n");
                    break;
                }
         break;
        }
     break;
    }

Having trouble with my code. It seems to skip the while loop. I've tried both fgets, scanf, and putting a getchar() after either. In either case it seems to not work with the ifs and else ifs. If I type "test" the input will indeed be test but it won't work as expected. Any help would be appreciated.

Upvotes: 1

Views: 53

Answers (2)

myradio
myradio

Reputation: 1775

First

You have a mistake,

scanf("%s", &command);

should be,

scanf("%s", command);

because scanf is defined,

int scanf(const char *format, ...);

Second

And then, to enter to the while loop, you want the string not to match 'kill', hence,

while(!strcmp(command, "kill"))

should be

while(strcmp(command, "kill"))

because, from strcmp help,

#include <string.h>
int strcmp(const char *s1, const char *s2);

The strcmp() and strncmp() functions return an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.

Upvotes: 1

harisu
harisu

Reputation: 1416

Note

strcmp in c returns 0 if the two strings are equal other wise it returns a non zero number you should endeavors to check it like below !(strcmp(str1,str2) ==0)

This should do the trick

Upvotes: 0

Related Questions