SlimShadys
SlimShadys

Reputation: 125

if statement always true even with right inputs?

I'm doing some checks for the month input in my project. I scanf 2 characters. Let's say I successfully have taken "10" as input. Then through an if statement I ask the compiler if the input taken is greater than 12 or lower than 01 , but in whatever occasion, the if statement is always true.

#define MAX_DAY 2
#define MAX_MONTH 2
#define MAX_YEAR 4

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

typedef struct {
    char day[MAX_DAY];
    char month[MAX_MONTH];
    char year[MAX_YEAR];
} date; //struct data

typedef struct {
    date date_of_flight;
} flight; //struct volo

int CheckMonth (flight list1);

int main() {

    flight list;

    int correct = 0;

    while (correct != 1) {
    printf("Month of departure: ");
    scanf("%2s", list.date_of_flight.month);
    correct = CheckMonth(list);
    }

    return 0;
}

int CheckMonth (flight list1) {

    int correct = 0;

    if ((list1.date_of_flight.month > 12) || (list1.date_of_flight.month < 01))  {
        printf("Wrong input. The right input should be between 01 (January) and 12 (December).\n");
    }
    else
    {
        correct = 1;
    }
    return correct;
}

If you're asking yourself why did I use char month[] instead of a simple int, it's because if I scanf "05" through an int, the scanf will only read 5.

Upvotes: 0

Views: 76

Answers (1)

Susmit Agrawal
Susmit Agrawal

Reputation: 3764

You need to compare strings in your function.

if ((list1.date_of_flight.month > 12) || (list1.date_of_flight.month < 01))  {
    printf("Wrong input. The right input should be between 01 (January) and 12 (December).\n");

should actually be:

if ((strcmp(list1.date_of_flight.month, "12") > 0 ) || (strcmp(list1.date_of_flight.month, "01") < 0))  {
    printf("Wrong input. The right input should be between 01 (January) and 12 (December).\n");
}

strcmp() is a function in <string.h>. It returns 0 if the two strings are equal.

It returns a negative number if the first different character in the first string comes after that in the second string, based on ASCII value.

Otherwise, it returns a positive number.

Upvotes: 3

Related Questions