Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _CRT_SECURE_NO_WARNINGS
- #include <cstdio>
- #include <string.h>
- #include <iostream>
- typedef struct {
- char** text;
- size_t sentences = 20;
- } TEXT;
- int getTextFromFile(TEXT*, FILE*, const char[40]);
- void showAllText(TEXT*);
- void showSentencesContains(TEXT*, char[80]);
- bool strCheck(const char*, const char*);
- int strStr(const char*, const char*);
- int main()
- {
- FILE* file = NULL;
- TEXT* Text = new TEXT;
- char word[80];
- const char fileName[40] = "Text.txt";
- printf("Please, input the word: ");
- scanf("%s", word);
- if (getTextFromFile(Text, file, fileName))
- //showAllText(Text);
- showSentencesContains(Text, word);
- else
- puts("#ERROR: Can't read data from file");
- system("pause");
- return 0;
- }
- int getTextFromFile(TEXT* Text, FILE* file, const char fileName[40])
- {
- if ((file = fopen(fileName, "r")) == NULL)
- {
- perror("Can't open file to read");
- return 0;
- }
- else
- {
- Text->text = (char**)malloc(sizeof(char*)*Text->sentences);
- char c;
- char currentString[1000] = "";
- size_t i = 0;
- size_t j = 0;
- do
- {
- c = fgetc(file);
- if (c == '.' && i < Text->sentences)
- {
- currentString[j] = '\0';
- Text->text[i] = (char*)malloc(sizeof(char) * (j + 1));
- strcpy(Text->text[i], currentString);
- i++;
- j = 0;
- }
- else if (c == '.' && i == Text->sentences)
- {
- Text->sentences *= 2;
- Text->text = (char**)realloc(Text->text ,sizeof(char*)*Text->sentences);
- currentString[j] = '\0';
- Text->text[i] = (char*)malloc(sizeof(char) * (j + 1));
- strcpy(Text->text[i], currentString);
- i++;
- j = 0;
- }
- else if (c == '\n' || c == '\0')
- {
- c = ' ';
- currentString[j] = c;
- j++;
- }
- else
- {
- currentString[j] = c;
- j++;
- }
- } while (c != EOF);
- fclose(file);
- return 1;
- }
- }
- void showAllText(TEXT* Text)
- {
- for (int i = 0; i < Text->sentences; i++)
- {
- printf("%s\n", Text->text[i]);
- }
- }
- void showSentencesContains(TEXT* Text, char word[80])
- {
- bool bingo = false;
- for (int i = 0; i < Text->sentences; i++)
- {
- for (int j = 0; ( j < strlen(Text->text[i]) - strlen(word) ) && !bingo; j++)
- {
- if ( strStr(Text->text[i], word) != -1)
- {
- printf("%s\n\n", Text->text[i]);
- bingo = true;
- }
- }
- bingo = false;
- }
- }
- bool strCheck(const char *p, const char *pattern)
- {
- for (; *pattern != '\0'; pattern++)
- {
- if (*p != *pattern)
- return false;
- p++;
- }
- return true;
- }
- int strStr(const char *text, const char *pattern)
- {
- if (*pattern == '\0')
- return 0;
- else if (*text == '\0')
- return -1;
- int N = strlen(text);
- for (int i = 0; i < N; i++)
- {
- if (strCheck(text + i, pattern))
- return i;
- }
- return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement