【发布时间】:2019-10-05 12:10:51
【问题描述】:
我正在检查项目中的月份输入。 我scanf 2个字符。假设我成功地将“10”作为输入。 然后通过 if 语句询问编译器输入是否大于 12 或小于 01 ,但在任何情况下,if 语句始终为真。
#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;
}
如果你问自己为什么我使用 char month[] 而不是简单的 int,那是因为如果我通过 int 扫描“05”,scanf 只会读取 5。
【问题讨论】:
-
一方面你的字符串对于 NUL 字符串终止符来说太短了,另一方面你正在比较一个字符串 pointer 和一个数字。请检查编译器警告。
-
我只是在
CheckMonth中的 if 语句之前使用了int val = atoi(list1.date_of_flight.month);。当然,还要比较(val > 12) || (val < 01)。还是谢谢你。 -
字符串仍然太短。输入
char month[MAX_MONTH+1];等。它似乎起作用的一个原因是该变量是全局变量,已初始化为全0,并且您尚未在其他字符串中输入数据。 -
明白了。现在我明白了。 :) 所以我应该输入
[MAX_MONTH+1]等,因为最后一个应该是'\0'? -
@SlimShadys 是的。
标签: c if-statement