0
votes

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.

1
For one thing your strings are too short for the NUL string terminator, and for another you are comparing a string pointer with a number. Please check compiler warnings.Weather Vane
I just figured it out by using int val = atoi(list1.date_of_flight.month); right before the if statement in CheckMonth. And also comparing (val > 12) || (val < 01) of course. Thank you anyways.SlimShadys
The strings are still too short. Put char month[MAX_MONTH+1]; etc. One reason it appears to work is that the variable is global, was initialised to all-0, and you have not entered data into the other strings.Weather Vane
Gotchu. Now I understood. :) So I should put [MAX_MONTH+1] and such because the last one should be '\0'?SlimShadys
@SlimShadys Yes.Swordfish

1 Answers

3
votes

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.