Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}

1 Answers

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 )
like image 186
Vlad from Moscow Avatar answered Dec 07 '25 20:12

Vlad from Moscow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!