【问题标题】:if statement always true even with right inputs?即使输入正确,if 语句也始终为真?
【发布时间】: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 &gt; 12) || (val &lt; 01)。还是谢谢你。
  • 字符串仍然太短。输入char month[MAX_MONTH+1]; 等。它似乎起作用的一个原因是该变量是全局变量,已初始化为全0,并且您尚未在其他字符串中输入数据。
  • 明白了。现在我明白了。 :) 所以我应该输入[MAX_MONTH+1] 等,因为最后一个应该是'\0'?
  • @SlimShadys 是的。

标签: c if-statement


【解决方案1】:

您需要比较函数中的字符串。

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()&lt;string.h&gt; 中的一个函数。如果两个字符串相等,则返回 0。

如果第一个字符串中的第一个不同字符在第二个字符串之后,则返回一个负数,基于 ASCII 值。

否则返回正数。

【讨论】:

  • 这也可以。我在 cmets 中提出了另一个解决方案。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 2021-01-07
  • 2012-03-07
  • 1970-01-01
  • 2019-05-20
相关资源
最近更新 更多