【问题标题】:Array not giving back letters the user entered数组不返回用户输入的字母
【发布时间】:2017-10-26 01:14:11
【问题描述】:
 int read_word(char word[], int max_size_word) {
 {
        int c = 0, let_count = 0;
        printf("\nPlease enter your word: ");
        char input = toupper(getchar());
        for(c = 1; c < 7; c++) {
            if(input != '\n') {
                word[c] = input;   
                let_count++;
            } else if(input == '\n')
              input = toupper(getchar());       //The word the user entered is in word[c]
            }
            return let_count;
         }
    }
    int check_word(char word[], int size_word, int letter_set[], int 
    size_letter_set, int arr[]) 
    {
        char word_copy;
        for(int ii = 0; ii < 7; ii++) {
            word_copy = word[ii];
        }
        printf("The word is %c\n" , word_copy);
    return 0;
}

我正在编写一个拼字游戏。这是与我的问题有关的两个功能。基本上我想检查我的阅读单词功能是否有效。这就是底部 printf 的作用。但是,当我输入几个字母时,我的“单词是....” printf 只返回输入的第一个字母。我希望 printf 回馈输入的每个字母。任何帮助将不胜感激!

【问题讨论】:

  • 如果你对文本进行了良好的格式化,你会看到你的最后一个 printf 在循环之外。
  • @serge 不会让“这个词是……”出现 7 次吗? -我刚刚测试了它,这就是它的作用
  • 是的,但是您打印的是单个字符,在任何情况下都不是一个字。这样你就可以一一看到数组中的所有字符。
  • @serge 当我在循环中测试它时它返回 单词是 E 单词是 G 单词 if G 等等..
  • 您是否尝试过“伪装成计算机”的技巧来了解您的程序为何无法正常运行?

标签: c arrays


【解决方案1】:

您只打印一个字母,因为在 printf("The word is %c\n" , word_copy); 中,您的 word_copy 是 char 而不是 string。
在 check_word 中,尝试替换

char word_copy;
        for(int ii = 0; ii < 7; ii++) {
            word_copy = word[ii];
        }
        printf("The word is %c\n" , word_copy);
    return 0;

由

int word_size = strlen(word); //calculate the length of your word
char word_copy[word_size + 1]; //create copy string with word size +1 for \0
int ii = 0;
        for(ii; ii < 7; ii++) { //I set ii < 7 to do like you but... Why did you set 7?
            word_copy[ii] = word[ii]; //put the characters of your word into the copy string
        }
    word_copy[ii] = '\0'; //end the string puttin a \0 at its end
    printf("The word is %s\n" , word_copy); //here i replace %c (char) by %s (string)
return 0;

您的read_word 函数中存在类似的问题,如果您了解我在您的check_word 函数中所做的修复,您应该能够修复它们(即使您可以将您的 printf 放在 for 循环中,我认为这样做可以帮助您理解 read_word 中的问题)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-06
    • 1970-01-01
    • 2020-03-06
    • 2019-09-26
    • 2012-08-08
    • 2020-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多