Counting the number of words from a text file in C++.

Hi there, I am trying to write a simple program where the number of words are counted from a text file.The program below reads the file correctly and then displays all the content too, but fails to show the correct size of the entire string and the number of words contained in it. Please note that the commented part of the code is the string that has been explicitly defined and all that exists in the text file as well. The reason why I included that is because if you uncomment that part and comment out the part where the program reads from the file (i.e lines 28 through 40), the program runs fine as the string will be explicitly defined. The only reason why I am trying to do this is to see if the program can read a string that has almost or more than 1000 words.

Here is the code:

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

class WordCount
{
private:
    int NOW,count;
    string theString;

public:
    WordCount()
    {
        NOW=1;
        count=0;
        //theString="A major change that has occurred in the Western family is an increased incidence in divorce. Whereas in the past, divorce was a relatively rare occurrence, in recent times it has become quite commonplace. This change is borne out clearly in census figures. For example thirty years ago in Australia, only one marriage in ten ended in divorce; nowadays the figure is more than one in three (Australian Bureau of Statistics, 1996: p.45). A consequence of this change has been a substantial increase in the number of single parent families and the attendant problems that this brings (Kilmartin, 1997).An important issue for sociologists, and indeed for all of society, is why these changes in marital patterns have occurred. In this essay I will seek to critically examine a number of sociological explanations for the 'divorce phenomenon' and also consider the social policy implications that each explanation carries with it. It will be argued that the best explanations are to be found within a broad socio-economic framework.One type of explanation for rising divorce has focused on changes in laws relating to marriage. For example, Bilton, Bonnett and Jones (1987) argue that increased rates of divorce do not necessarily indicate that families are now more unstable. It is possible, they claim, that there has always been a degree of marital instability. They suggest that changes in the law have been significant, because they have provided unhappily married couples with 'access to a legal solution to pre-existent marital problems' (p.301). Bilton et al. therefore believe that changes in divorce rates can be best explained in terms of changes in the legal system. The problem with this type of explanation however, is that it does not consider why these laws have changed in the first place. It could be argued that reforms to family law, as well as the increased rate of divorce that has accompanied them, are the product of more fundamental changes in society.Another type of explanation is one that focuses precisely on these broad societal changes. For example, Nicky Hart (cited in Haralambos, 1995) argues that increases in divorce and marital breakdown are the result of economic changes that have affected the family. One example of these changes is the raised material aspirations of families, which Hart suggests has put pressure on both spouses to become wage earners. Women as a result have been forced to become both homemakers and economic providers. According to Hart, the contradiction of these two roles has lead to conflict and this is the main cause of marital breakdown. It would appear that Hart's explanation cannot account for all cases of divorce - for example, marital breakdown is liable to occur in families where only the husband is working. Nevertheless, her approach, which is to relate changes in family relations to broader social forces, would seem to be more probing than one that looks only at legislative change.The two explanations described above have very different implications for social policy, especially in relation to how the problem of increasing marital instability might be dealt with. Bilton et al. (1995) offer a legal explanation and hence would see the solutions also being determined in this domain. If rises in divorce are thought to be the consequence of liberal divorce laws, the obvious way to stem this rise is to make them less obtainable. This approach, one imagines, would lead to a reduction in divorce statistics; however, it cannot really be held up as a genuine solution to the problems of marital stress and breakdown in society. Indeed it would seem to be a solution directed more at symptoms than addressing fundamental causes. Furthermore, the experience of social workers, working in the area of family welfare suggests that restricting a couple's access to divorce would in some cases serve only to exacerbate existing marital problems (Johnson, 1981). In those cases where violence is involved, the consequences could be tragic. Apart from all this, returning to more restrictive divorce laws seems to be a solution little favoured by Australians. (Harrison, 1990).Hart (cited in Haralambos, 1995), writing from a Marxist-feminist position, traces marital conflict to changes in the capitalist economic system and their resultant effect on the roles of men and women. It is difficult to know however, how such an analysis might be translated into practical social policies. This is because the Hart program would appear to require in the first place a radical restructuring of the economic system. Whilst this may be desirable for some, it is not achievable in the present political climate. Hart is right however, to suggest that much marital conflict can be linked in some way to the economic circumstances of families. This is borne out in many statistical surveys which show consistently that rates of divorce are higher among socially disadvantaged families (McDonald, 1993). This situation suggests then that social policies need to be geared to providing support and security for these types of families. It is little cause for optimism however, that in recent years governments of all persuasions have shown an increasing reluctance to fund social welfare programs of this kind.It is difficult to offer a comprehensive explanation for the growing trend of marital breakdown; and it is even more difficult to find solutions that might ameliorate the problems created by it. Clearly though, as I have argued in this essay, the most useful answers are to be found not within a narrow legal framework, but within a broader socio-economic one.Finally, it is worth pointing out that, whilst we may appear to be living in a time of increased family instability, research suggests that historically, instability may have been the norm rather than the exception. As Bell and Zajdow (1997) point out, in the past, single parent and step families were more common than is assumed - although the disruptive influence then was not divorce, but the premature death of one or both parents. This situation suggests that in studying the modern family, one needs to employ a historical perspective, including the possibility of looking to the past in searching for ways of dealing with problems in the present.";
    }

    void theCounter()
    {
        ifstream in;
        in.open("Essay.txt");

        if(!in)
        {
            cerr << "Error loading file." << endl;
            exit(0);
        }

        while(!in.eof())
        {
            while(getline(in,theString))
            {
                cout << theString << endl;
            }
        }

        for(int i=0;i<theString.size();i++)
        {
            if(theString[i]==' ')NOW++;
        }

        cout << endl << "Number of words: " << NOW << endl << endl;

        in.close();
    }
};


int main()
{
    WordCount c;
    c.theCounter();

    return 0;
}


Thank you :)
Last edited on
Why are you using int/string POINTERS?
What's the point???
well i just used pointers to dynamically allocate memory cause I was thinking that maybe due to less memory, I wasnt getting my desired results. That was until I explicitly defined the string, but then i just didnt change the code.
Nah, std::string doesn't use stack memory, it gets automatically resized.
Your program is only counting the words in the last line of your file.
getline overwrites your *theString contents.

Plus a (probably necessary) comment: your loop is actually counting spaces.
This means words separated by comma, colon, semicolon and other symbols aren't being really counted, and you can add multiple spaces at the end of the line to increase your word count without actually noticing.
Thank you very much for the advice. You are right, getline only counts the words in the last line. I didn't know that! So yea, I have changed the code and gotten rid of all the pointers. I'll do a little more digging and get back to you on this. :)
@S G H thank you so much. What you said about getline was the main reason why the program wasnt working. But I fixed it now and it works fine. Thanks again and God bless :)
Topic archived. No new replies allowed.