簡體   English   中英

程序未正確注冊我的輸入

[英]Program not registering my input correctly

#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。 這是問題所在嗎? 有什么建議么?

您可以通過反轉對checkAnswer()調用中的術語來避免BLUEPIXY提到的\\n (換行符)的問題-即, gets()刪除了它,而fgets()並未刪除它:

checkAnswer(answer, strGame[x]);

然后, checkAnswer()strstr()使用相同的順序。 如果在“ foobar \\ n”中搜索“ foobar”, strstr()將返回一個指針。 但是,如果您在“ foobar”中搜索“ foobar \\ n”,則不會。

因為用戶點擊Enter ,所以出現了換行符。 因此,另一種解決方法是在所有strGame[]字符串的末尾添加一個\\n 或者,您可以使用以下方法刪除答案中的所有換行符:

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

問題是fgets()將換行符留在字符串的末尾。 鍵入單詞時,請按Enter鍵,fgets()會將其解釋為輸入。

因此,一種繞過此方法的方法是通過執行以下操作來換行:

fgets(answer, 80, stdin);
// go to the last position where the
// newline is placed and replace it
// with the null terminator
answer[strlen(answer)-1] = '\0';

也在這里:

 for (x = 0; x <= strlen(string2); x++)
    string2[x] = toupper(string2[x]);

不需要<= ,因為您從0開始,因此將其更改為:

 for (x = 0; x < strlen(string2); x++)
    string2[x] = toupper(string2[x]);

我怎么發現你的問題? 在比較它們之前,我使用了printf來輸出字符串。

void checkAnswer(char *string1, char string2[]) {
  int x;

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

}

我的修復之前的輸出:

|ADELANGUAGEFERVZOPIBMOU|
|ADEL
|

修復后的輸出:

|ADELANGUAGEFERVZOPIBMOU|
|ADEL|

或者,您可以使用函數來修剪換行符和空格。 這里有一些方法。

還考慮不使用system()

而且,總是添加一個return 0; main()結束之前的代碼行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM