guest
guest

Reputation: 9

I cant seem to print out the total number a word occurs in a .txt file in c?

I have the code below. I am trying to ask the user for an input that will then be compared to a .txt file (that I put into a 1D array). I think the while loop and the if statement is not working because I try to print out the arrays/count from those loops and I don't get anything printed from them.

#include "defs.h"

void searchForWord(char allLines[MAX_LINE][MAX_LINE_LEN], int numLines)
{
    FILE *inputFile;
    char inputWord[20];
    char tempOneD[15000];
    int inputCount = 0;
    int i = 0, j = 0, k = 0, l = 0;
    char tempArr[20];

    inputFile = fopen("poe-raven.txt", "r");

    //input for word wanting to be searched
    printf("Search for what word?");
    scanf("%s", inputWord);

    //inputs the number of rows
    for (i = 0; i < numLines; i++) {
        //inputs the number of colums
        for (j = 0; j < MAX_LINE_LEN; j++) {
            if (allLines[i][j] == '\0') {
                tempOneD[k] = allLines[i][j];
                k++;

                //clears the tempArr array
                for (l = 0; l < MAX_LINE_LEN; l++) {
                    tempArr[l] = '0';
                }

                l = 0;

                //puts the value from the 1D array into a temp array
                while (fscanf(inputFile, "%s", tempArr)) {
                    tempArr[l] = allLines[i][j + l];
                    printf("%s", tempArr);
                    l++;



                    //checks to make sure that the two strings match and arent inside
                    //of another word.
                    if ((strcasecmp(tempArr, inputWord) == 0) && !isalpha(allLines[i][j - l])) {
                        inputCount++;
                        printf("%d", inputCount);
                    }
                }
            }
        }
    }


    printf("\n> %s < appears %d times\n", inputWord, inputCount);
}

Upvotes: 0

Views: 32

Answers (1)

Swordfish
Swordfish

Reputation: 13134

To count the occurrences of a word within a file you could do something like this:

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

#ifdef _MSC_VER  // msvc doesn't know about strncasecmp() 
#define strcasecmp _stricmp  // but has _stricmp() instead
#endif

// macros to "stringify" a preprocessor symbol like MAX_WORD_LENGTH
#define STR(X) #X
#define STRING(X) STR(X)

// #define FOO 10
// STRING(FOO) would get replaced with "10"
// so it can be used in strings: "foo"STRING(FOO)"bar" ~> "foo""10""bar"
//                                   which is the same as "foo10bar"

#define MAX_WORD_LENGTH 80

char* strip_punctuation(char *word)
{
    size_t length = strlen(word);
    size_t first_letter = 0;

    // get the index of the first letter:
    for (char *p = word; *p && !isalpha((char unsigned)*p); ++first_letter, ++p);
    //                                  ^^^^^^^^^^^^^^^ don't feed functions from
    //                                   <ctype.h> negative values!

    // strip everything that isn't a letter from the back of the string:
    for (char *p = word + length - 1; p != word && !isalpha((char unsigned)*p); --p, --length)
        *p = '\0';

    // move the string first_letter positions to the left:
    for (size_t i = 0; i <= length - first_letter; ++i)
        word[i] = word[i + first_letter];

    return word;
}

size_t count_occurrences(FILE *is, char const *word_to_count)
{
    char word[MAX_WORD_LENGTH + 1];
    size_t counter = 0;

    // read the file word by word and compare against word_to_count:
    while (fscanf(is, "%"STRING(MAX_WORD_LENGTH)"s", word) == 1)
        if (strcasecmp(strip_punctuation(word), word_to_count) == 0)
            ++counter;

    return counter;
}

int main(void)
{
    char word_to_count[MAX_WORD_LENGTH + 2];  // + 1 for the newline + 1 for the terminating '\0';
    if (!fgets(word_to_count, sizeof(word_to_count), stdin)) {
        fputs("Input error :(\n\n", stderr);
        return EXIT_FAILURE;
    }

    size_t length = strlen(word_to_count);
    if (length && word_to_count[length - 1] == '\n')
        word_to_count[--length] = '\0';

    char const *filename = "test.txt";
    FILE *is = fopen(filename, "r");
    if (!is) {
        fprintf(stderr, "Couldn't open \"%s\" for reading :(\n\n", filename);
        return EXIT_FAILURE;
    }

    size_t occurrences = count_occurrences(is, word_to_count);
    printf("\"%s\" occurs %zu times in \"%s\".\n", word_to_count, occurrences, filename);
    fclose(is);
}

Upvotes: 1

Related Questions