0

The difference between the BUG version and the BUG-free version is: In the freCount() of the BUG-free version, the char array "word" is directly defined instead of being read in through the fgets().

BUG version: (if you enter the main string as "domanmanman", the result is 1)

#include<stdio.h>
#include<string.h>
#define MAX 3000
int main(){
    char str[MAX]; 
    printf("Enter the text:\n");
    fgets(str, sizeof(str), stdin);
    
    freCount(str);
}
void freCount(char* str) {
    int cntWord = 0;
    char word[MAX];
    printf("Enter the string you want to count:\n");
    fgets(word, sizeof(word), stdin);
 
    for (int j = 0; j <= strlen(str) - strlen(word); j++) {
        int k;
        for (k = 0; k < strlen(word); k++) {
            if (str[j + k] != word[k])
                break;
        }
        if (k == strlen(word)) {
            cntWord++;
            k = 0;
        }
    }
    printf("The frequency of the string is:%d\n", cntWord);
}

BUG-free version:

#include<stdio.h>
#include<string.h>
#define MAX 3000
void freCount(char* str);
int main(){
    char str[MAX]; 
    printf("Enter the text:\n");//To facilitate testing, please enter "domanmanman"
    fgets(str, sizeof(str), stdin);
    
    freCount(str);
    return 0;
}
void freCount(char* str) {
    int cntWord = 0;
 
    char word[MAX] = { "man" };
 
    for (int j = 0; j <= strlen(str) - strlen(word); j++) {
        int k;
        for (k = 0; k < strlen(word); k++) {
            if (str[j + k] != word[k])
                break;
        }
        if (k == strlen(word)) {
            cntWord++;
            k = 0;
        }
    }
    printf("The frequency of the string is:%d\n", cntWord);
}
MuSk7777
  • 1
  • 1
  • 1
    At least make it `fgets(str, sizeof(str)-1` for room of the terminating null. Same for `word` – Paul Ogilvie Jun 28 '21 at 08:46
  • 3
    @PaulOgilvie _"fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (aq\0aq) is stored after the last character in the buffer. "_ – YSC Jun 28 '21 at 08:50
  • 2
    I didn't check your code, but are you aware that a string read with `fgets` has a trailing `\n`? – Jabberwocky Jun 28 '21 at 08:50
  • `fgets` leaves the terminating `\n` in the string read. You must remove it. – Paul Ogilvie Jun 28 '21 at 08:51
  • 1
    You might better see such a problem by running your program in a debugger to check the variable values or by printing string values enclosed in delimiting characters, e.g. `printf("The string you just entered is:\n\n", word);` – Bodo Jun 28 '21 at 08:59
  • @PaulOgilvie It works! I use 'word[strlen(word)-1] = '\0'; to implement it. But why \n will effect it? – MuSk7777 Jun 28 '21 at 11:01
  • Because you then are comparing to a word that includes a newline. – Paul Ogilvie Jun 28 '21 at 14:02

0 Answers0