JangoCG
JangoCG

Reputation: 976

if statement with string compare in C

I'm supposed to write a short C code where I generate a random number between 1 and 6 if I type "random". If I type in "exit" or "quit", the program must end. "quit" and "exit" work, but nothing happens when I enter "random".

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

int main() {
    printf("enter your command");
    char input[100];
    fgets(input, 100, stdin);

    if (strcmp(input, "quit") == 0){
       exit(0); 
    } else if (strcmp(input, "exit") == 0) {
       exit(0);
    } else if (strcmp(input, "random") == 0) {
       srand(time(NULL));
       int random_number = rand() %7;
       printf("%d\n",random_number);     
    }
    return 0;
}

Upvotes: 3

Views: 1432

Answers (2)

sidyll
sidyll

Reputation: 59277

Your fgets call is reading the inserted command plus the newline at the end. So you should compare with the newline as well, or choose a different input reading method (such as using scanf, useful for dealing with any whitespace, or removing the newline yourself).

strcmp(input, "quit\n") == 0
strcmp(input, "exit\n") == 0
strcmp(input, "random\n") == 0

You didn't notice with the first two commands, but they never passed the test as well.

You could also add a final else to grab anything not matched. Only altering that (without dealing with newlines) would prove that the others are not matching as well:

/* ... */
} else {
    printf("unknown command\n");
}

An example using scanf:

char input[101];
scanf(" %100s", input); /* discards any leading whitespace and
                         * places the next non-whitespace sequence
                         * in `input` */

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 310940

You need to remove the new line character '\n' that can be appended to the string read by fgets.

For example

char input[100];
input[0] = '\0';

if ( fgets (input, 100, stdin) )
{
    input[strcspn( input, "\n" )] = '\0';
}

Take into account that the initializer in this declaration

int random_number = rand() %7;

generates numbers in the range [0, 6]. If you need the range [1, 6] then the initializer should look like

int random_number = rand() %6 + 1;

And according to the C Standard the function main without parameters shall be declared like

int main( void )

Upvotes: 4

Related Questions