Как считать слова, которые по отдельности пересекаются друг с другом в текстовом файле - PullRequest
0 голосов
/ 28 декабря 2018

Я ищу в текстовом файле, который выбрал пользователь, чтобы найти конкретные слова и символы (&), которые уже определены библиотекой.Я сделал отдельную функцию для каждого слова (потому что я не знаю, как их объединить), но я не могу понять функцию поиска do / while.

Я сделал отдельную функцию для каждого слова,но я не могу понять функцию поиска do / while, в сущности, проблема, с которой я столкнулся, заключается в объединении функций и поиске только двух частей слова.Я хочу считать пока и делаю / пока разделен.

 #include < stdio.h >
#include < stdlib.h >
#include < string.h >
#define BUFFER_SIZE 1000

/* Function declarations. How do I combine them all? */
int CountOccurrences ( FILE *fptr, char *word );

int main()
{
    FILE *fptr; // name

    SetConsoleCP (1251); // so that it runs with my language 
    SetConsoleOutputCP (1251);

    char path[100];

    // The 4 words and the symbol I am searching for.

    char word[]= "while";
    char word1[]= "for";
    char word2[]= "&";
    char word3[]= "do{ }while";

    int wCount; // Variable to get the value of the function.
    int wCount1; // same 
    int wCount2; // same 
    int wCount3; // same 

    /* Input file path */
    printf ( "Enter file path: " );
    scanf ( "%s", path );

    /* Try to open file */
    fptr = fopen ( path, "r" );

    /* Exit if file not opened successfully */
    if ( fptr == NULL )
    {
        printf ( "Unable to open file.\n" ); //Error msg
        printf ( "Please check you have read/write previleges.\n" ); //Help msg

        exit(EXIT_FAILURE); //end
    }

     // Call function to count all occurrence of word
    wCount = CountOccurrences ( fptr, word );
     //rewind so I can use It again

    rewind ( fptr );
    printf ( "'%s' is found %d times in file.\n", word, wCount );

    //the method is the same for all the 4 functions        
    fclose ( fptr ); //close file

    return 0;  /* How can I search for overlapping words in a txt file with the goal to differentiate from each other in a txt file */ 
}

 //Returns total occurrences of a word in given file.
 int CountOccurrences(FILE *fptr, char *word) {

    char str [BUFFER_SIZE]; //The other functions are the same
    char *pos;

    int index, count;

    //make a variable to count the amount of occurrences 

    count = 0;

    // Read line from file till end of file.
    while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
    {
        index = 0; //to store the word

        // Find next occurrence of word in str
        while ((pos = strstr(str + index, word)) != NULL)
        {
            index = (pos - str) + 1;

             // Index of word in str is
             // Memory address of pos - memory
             // address of str.

            count++; // sums every time for a specific word
        }
    }
    return count; 
}

1 Ответ

0 голосов
/ 28 декабря 2018

В функции CountOccurances () ниже в цикле while, используя strcmp () для каждого из word1, word2, word3 и word4, можно найти слова.

  while ((pos = strstr(str + index, word))

Далее в функции fgets (), символ новой строки будет прочитан в конце чтения слова, что может привести к сбою strcmp ().Это можно сделать, сделав последний символ слова минус 1 равным нулю

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...