A problem with c++ program

I have a problem. I want to make a programm what counts words and then shows how many word there are in total and how often each word is in the text file.
for example:
There are 190 word in Sun.txt file:
25 Sun
19 is
18 then
18 and
etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <stdio.h>
#include <string.h>
#define N 200

using namespace std;
int main()
{
    char words[N][200];
    int count[N];
    const char *failinimi=
    "C:\\Work\\T.txt"; 
    FILE *fp; 
    char line[120];
    int lines=0, i=0, j, chars=0, words=0, characters=0, counter[26], max=0;
    char character;
    fp=fopen(filename, "r");
    if(!fp){printf("Cannot find the %s file!\n", filename); return 1;}
    for(i=0;i<26;counter[i++]=0);
    while(!feof(fp)){
        fgets(line, 120, fp); lines++, i=0;
        if(line[0]=='\n')continue;
        while(character=line[i++]){
            if(character!='\n')characters++;
            else words++;
            if(character==' ')words++;
            if(character>='A'&& character<='Z'){characters++; counter[character-'A']++;}
            if(character>='a'&& character<='z'){characters++; counter[character-'a']++;}
    }
        while(!feof(fp)){
        fgets(line, sizeof(line), fp);
        strtok(line, " ");
        strcpy(words[i],strtok(NULL, "\n"));
        strtok(words[i], " ");
        counter[i]=1;
        for(j=0;j<i;j++)if(!strcmp(words[i], words[j]))counter[i]++;
        if(counter[i]>max)max=counter[i];
        printf("%d. %s\n", counter[i], words[i]);
        i++;
    }
    }
    fclose(fp);
    printf("Statistic of file T.txt is :\n");
    printf("\t %3d word\n", words);
}[code]
[/code]
Last edited on
closed account (4z0M4iN6)
I wouldn' stuff all into one function:

you shoud have:

- a function readfile(), which reads lines until the end of the file
- a function separatewords( char * line) wich separates the words of the line
- a function manageword( char *word), which counts words and compares the word with words in a list.
- if the word already exists in the list, a counter for this word entry will be increased
- if not, the word will be appended to the list


if you make such small functions, each doing only a part of the work, all becomes clear.
Last edited on
Topic archived. No new replies allowed.