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.
int val = atoi(list1.date_of_flight.month);
right before the if statement inCheckMonth
. And also comparing(val > 12) || (val < 01)
of course. Thank you anyways. – SlimShadyschar 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[MAX_MONTH+1]
and such because the last one should be'\0'
? – SlimShadys