C程序循环循环通过getchar/ fgets

问题描述

我有一个拼写检查程序,要求用户输入一个单词进行拼写检查。然后,基于结果,可能需要输入“ y”或“ n”作为响应。 为此,我正在使用getchar()和fgets()。两者都位于while循环中。 我注意到一种奇怪的行为,因为该程序有时会在getchar()/ fgets()暂停等待输入之前多次运行while循环。有人知道为什么吗? 完整代码如下:

//
//  main.c
//  Assignment 2
//  Jared larson
//  11/4/20

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

#define MAX_WORD_LEN 40
#define MAX_WORDS 110000
#define MIN(a,b) (((a)<(b))?(a):(b))
#define MAX(a,b) (((a)>(b))?(a):(b))

char wordlist[MAX_WORDS][MAX_WORD_LEN];

void pop_array(const char *cmd);
void get_word(char *in);
int hammer(char* dict,char* word,int index);

int main(int argc,const char * argv[]) {
    char word[MAX_WORD_LEN] = {};
    int max_ham = 1;
    pop_array(argv[1]);
    get_word(&word);
    
    while(strlen(word) != 0){
        
        int index = 0,cor_index = 0;
        char corrections[5][MAX_WORD_LEN] = {};
        char success[MAX_WORD_LEN] = {};
        int repeat_flag = 0;
        
        while(index <= MAX_WORDS){
            if(strlen(word) == strlen(wordlist[index])){
                int ham = hammer(wordlist[index],word,0);
                if(ham == 0){
                    strcpy(success,wordlist[index]);
                    break;
                }else if(ham <= max_ham && strlen(corrections) != 5){
                    strcpy(corrections[cor_index++],wordlist[index]);
                }
            }
            index++;
        }
        
        if(strlen(success)!=0){
            printf("The entered word: \"%s\" is spelled correctly! Nice one!!\n",success);
        }else if(corrections[0][0] != '\0'){
            printf("The entered word is misspelled. Suggestions within a hamming distance of %d:\n",max_ham);
            for(int i = 0; corrections[i][0] != '\0'; i++){
                printf("%s\n",corrections[i]);
                }
        }else{
            printf("The entered word is misspelled and there are no suggestion within %d hamming distance of the word.\n",max_ham);
            printf("Would you like to broaden your search by increasing the hamming distance to %d? \n",max_ham + 1);
            char answer;
            do{
                answer = NULL;
                printf("Please enter a 'y' for yes or 'n' for no: ");
                answer = getchar(); //<----------------This will repeat sometimes
                printf("\n");
                if(answer == 'y')
                    repeat_flag = 1;
            }while(!(answer == 'y' || answer == 'n'));
        }
        if(repeat_flag == 0){
            printf("\nExiting search...\n");
            get_word(&word);
            repeat_flag = 0;
            max_ham = 0;
        }else{
            max_ham++;
        }
    }
}
//pop_array accepts one parameters and has a void return type. pop_array opens a file pointed to by the parameter,reads in words one line at a time and stores them in the globally accessible wordlist[][].
void pop_array(const char *cmd){
    //FILE *fptr = fopen(cmd,"r");
    FILE *fptr = fopen("/Users/j-larhustle/Desktop/Fall 2020/247/C/Assignment 2/Full_wordlist.txt","r");
    if(fptr == NULL){
        printf("File object not found.");
        exit(-1);
    }
    char line[40] = {};
    
    int index = 0;
    while(fgets(line,MAX_WORD_LEN,fptr)){
        sscanf(line,"%s",&wordlist[index]);
        index++;
    }
    fclose(fptr);
}
//get_word accepts a character pointer as a parameter. This paramater points to the character array word[][] in main(). get_word prompts the user for a word input,converts it to lower-case and removes the '\n' character and stores the value in the character array word[][] in main().
void get_word(char *in){
    printf("Please enter a word to spellcheck: \n");
    fgets(in,stdin); //<----------------------This also sometimes does not stop to accept input.
    int i = 0;
    while(in[i]!='\n'){
        in[i] = (tolower(in[i]));
        i++;
    }
    in[i] = '\0';
}
//hammer accepts three parameters: a pointer to the dictionary word being compared to,a pointer to the word that the user input and an integer index. hammer recursively evaluates each index value starting at the zero index and continuing until the entire length of the user supplied word has been compared.
//hammer returns the integer value of the hamming distance.
int hammer(char* dict,int index){
    int value;
    if(index >= strlen(word)){
        return 0;
    }else{
        value = MAX(word[index],dict[index]) - MIN(word[index],dict[index]);
    }
    return value + hammer(dict,++index);
}

我已经附上了重复的屏幕截图。enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)