所以,程序的作用是,你用键盘写一天,然后验证它。您的输入可以是小写或大写。 问题是当我星期四给它几天。你可以看到contor得到奇怪的值。 length_arr是我用来测量数组长度的函数。 有什么建议吗?
int length_arr(char* x)
{
int i, length;
for (i = 0; x[i] != '\0'; 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);
}
答案 0 :(得分:0)
当您输入thursday
时,第一个t
与t
中的第一个tuesday
匹配,其余数组与hursday
匹配thursday
- 所以最终contor2
为1
而contor4
为7
。在条件中查看输入是否有效,检查是否有任何contor值是字符串的全长,它不会是因为星期四有8个字符。