gpt4 book ai didi

c - 程序没有正确注册我的输入

转载 作者:太空宇宙 更新时间:2023-11-04 00:05:50 25 4
gpt4 key购买 nike

#include <stdlib.h>
#include <time.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

//function prototypes
void checkAnswer(char *, char[]);
int main(void) {
char *strGame[5] = { "ADELANGUAGEFERVZOPIBMOU", "ZBPOINTERSKLMLOOPMNOCOT",
"PODSTRINGGDIWHIEEICERLS", "YVCPROGRAMMERWQKNULTHMD",
"UKUNIXFIMWXIZEQZINPUTEX" };
char answer[80] = { 0 };
int displayed = 0;
int x;
int startTime = 0;
system("clear");
printf("\n\n\tWord Find\n\n");
startTime = time(NULL);
for (x = 0; x < 5; x++) {
/* DISPLAY TEXT FOR A FEW SECONDS */
while (startTime + 3 > time(NULL)) {
if (displayed == 0) {
printf("\nFind a word in: \n\n");
printf("%s\n\n", strGame[x]);
displayed = 1;
}
}
system("clear");
printf("\nEnter word found: ");
fgets(answer, 80, stdin);
checkAnswer(strGame[x], answer);
displayed = 0;
startTime = time(NULL);
}
}
void checkAnswer(char *string1, char string2[]) {
int x;

for (x = 0; x <= strlen(string2); x++)
string2[x] = toupper(string2[x]);
if (strstr(string1, string2) != 0)
printf("\nGreat job!\n");
else
printf("\nSorry, word not found!\n");

}

当我运行代码时,它没有正确注册我的输入。它告诉我找不到这个词。我使用 toupper 使我的输入与我的字符串相同,并使用 strstr 将我的输入与字符串进行比较。我从一本基本的 C 编程书籍中得到了这个。它使用获取。我知道您不应该使用 gets,所以我将其更改为 fgets。这是问题所在吗?有什么建议吗?

最佳答案

您可以避免 BLUEPIXY 提到的 \n(换行符)的问题——即 gets() 将其删除但 fgets() 不会——通过反转您对 checkAnswer() 的调用中的条款:

checkAnswer(answer, strGame[x]);

checkAnswer() 然后使用与 strstr() 相同的顺序。如果您在“foobar\n”中搜索“foobar”,strstr() 将返回一个指针。但是如果你在“foobar”中搜索“foobar\n”,它不会。

换行符在那里是因为用户点击了 Enter。因此,另一种解决方法是将 \n 添加到所有 strGame[] 字符串的末尾。或者,您可以删除答案中的任何换行符:

void truncateAtNewline (char *str) {
char *p = strchr(str, '\n');
if (p) *p = '\0';
}

关于c - 程序没有正确注册我的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24596257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com