数组不返回用户输入的字母

时间:2017-10-26 01:14:12

标签: c arrays

 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的作用。然而,当我输入几个字母时,我的“The word is ....”printf只返回输入的第一个字母。我希望printf回馈每一个输入的字母。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分: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中的问题。