我正在对我的项目中的月份输入进行一些检查。我扫描了 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。
您需要比较函数中的字符串。
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");
实际上应该是:
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()
是 中的一个函数<string.h>
。如果两个字符串相等,则返回 0。
如果第一个字符串中的第一个不同字符在第二个字符串中之后,则基于 ASCII 值,它返回一个负数。
否则,它返回一个正数。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句