C编程,char*长度不能覆盖整个Array

C programming, char* length cannot cover the whole Array

因此,该程序所做的是,您从键盘上写下一天,他会对其进行验证。您的输入可以是小写或大写。 问题是当我在星期四给它几天。你可以看到 contor 得到了奇怪的值。 length_arr 是我用来测量数组长度的函数。 有什么建议吗?

int length_arr(char* x)
{

    int i, length;
    for (i = 0; x[i] != '[=10=]'; i++) {
    }

    return length = i - 1;
}

void valid_weekday(char* day)
{
    bool incorrect = true;
    char *monday = "monday", *tuesday = "tuesday", *wednesday = "wednesday", *thursday = "thursday", *friday = "friday", *saturday = "saturday", *sunday = "sunday";

    while (incorrect) {
    int contor1 = 0, contor2 = 0, contor3 = 0, contor4 = 0, contor5 = 0, contor6 = 0, contor7 = 0;
    //printf("NOTE: Weekday can contain uppercase letters. Why? Because reasons.\n\n");
    printf("Enter a valid weekday, please!:\n");
    fgets(day, 20, stdin);

    for (int i = 0; i < length_arr(day); i++) {

        if (day[i] == monday[i] || (int)monday[i] == (int)day[i] + 32) {
            contor1++;
            //.. To understand where i stops.
            printf("%c\n", day[i]);
        }
        else if (day[i] == tuesday[i] || (int)tuesday[i] == (int)day[i] + 32)
            contor2++;
        else if (day[i] == wednesday[i] || (int)wednesday[i] == (int)day[i] + 32)
            contor3++;
        else if (day[i] == thursday[i] || (int)thursday[i] == (int)day[i] + 32)
            contor4++;
        else if (day[i] == friday[i] || (int)friday[i] == ((int)day[i] + 32)) {
            contor5++;
            // ... To understand where i stops. (i stops at 2)
            printf(" day %c\n", day[i]);
            printf(" friday %c\n", friday[i]);
        }
        else if (day[i] == saturday[i] || (int)saturday[i] == (int)day[i] + 32)
            contor6++;
        else if (day[i] == sunday[i] || (int)sunday[i] == (int)day[i] + 32)
            contor7++;
    }
    if (contor1 == length_arr(day) || contor2 == length_arr(day) || contor3 == length_arr(day) || contor4 == length_arr(day) || contor5 == length_arr(day) || contor6 == length_arr(day) || contor7 == length_arr(day)) {
        printf("Good, you entered good.\n");
        incorrect = false;
    }
    else
        printf("Wrong day format!\n");

    // Tests to understand why other contor get value too
    int a = (int)day[0] - 32;
    printf("%d\n", (int)day[3]);
    printf("%d\n", a);
    printf("%d\n", (int)friday[3]);
    printf("%d\n", contor1);
    printf("%d\n", contor2);
    printf("%d\n", contor3);
    printf("%d\n", contor4);
    printf("%d\n", contor5);
    printf("%d\n", contor6);
    printf("%d\n", contor7);
    if ((int)monday[0] == a)
        printf("one");
    else
        printf("two");
    }
}

void main()
{
    char* day;
    day = new char(20);
    valid_weekday(day);
    delete (day);
}

当您输入 thursday 时,第一个 t 匹配 tuesday 中的第一个 t,数组的其余部分匹配 hursdaythursday - 所以你最终得到 contor21contor47。在您查看输入是否有效的条件中,您检查是否有任何 contor 值是字符串的全长,这不会是因为星期四其中有 8 个字符。