Word counter prevents program from working properly

For this program I need to read in "commands.txt". If it's empty I will display "commands.txt is empty". So I create a small block of code that counts the number of words in the "commands.txt" file and if it = 0. I display the message. This works when "commands.txt" is empty, but the moment I include it with text that should make the rest of my code work, nothing gets displayed on the console. It seems like the first and second while loops fight each other in a way that makes the program not working. Help would be great thanks.

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
60
61
  int main()
{
// Read the commands.txt file
    ifstream fin("commands.txt");
    if (fin.fail())
    {
        error("Could not open \"commands.txt\". Please make sure the file is in the same folder.");
    }

    //it seems like this while loop is the reason why it's not 
    int c = 0;
    string cstring = "";
    while (fin >> cstring)
    {
        ++q;
    }
    if (c == 0)
    {
        cout << "Commands.txt is empty";
    }




    string result = "";
    while(!fin.eof())
    {
        getline(fin,result);
        if (result == "")
        {
            break;
        }

        vector<string> words = {"",""};
        line_to_vector(result, words);


        if (words[0] == "num_chars")
        {
            num_chars(words);
            result = "";
        }
        else if(words[0] == "num_lines")
        {
            num_lines(words);
            result = "";
        }
        else if (words[0] == "num_words")
        {
            num_words(words);
            result = "";
        }
        else
        {
            cout << words[0] << "is not a recognized command. Terminating program.";
            error("command not recognized");
        }

    }

}
Problem #1: Line 15 - shouldn't this be ++c not ++q???

Problem #2: Your while (fin >> cstring) loop keeps pulling data out of the file until it there's nothing left (i.e. end of the file). Then it has reached the end of the file. Then there's no more data to be read. So testing !fin.eof() will always evaluate as false.

Put the followng at line 23 to prove this to yourself:
std::cout << "Is there any more data to be read? " << ((!fin.eof())?"Yes:-)":"No:-(") << std::endl;

So, before your while(!fin.eof()) loop on line 26, you need to reset to the beginning of the file. You could do this with seekg or you could close & reopen the file. I would say the better solution is to go with seekg.
Topic archived. No new replies allowed.