Hi I am trying to count the number of words in a file and this is what i have so far. I am not sure about the getchar().. could you please tell me what i should be doing ?

#include<iostream>
#include<fstream>
#include<string>
#include<conio.h>
using namespace std;

int main() {
        string line;
        int size=0, count_words=0;
        char c;
        ifstream myfile("example.rtf");
        if(myfile.is_open()) {
                while (!myfile.eof()) {
                        getline(myfile,line);
                        cout<<line<<endl;
                        size++;

                }

                cout<<"number of lines "<<size<<endl;

        getchar(myfile,c);
        cout<<c<<endl;


        myfile.close();

        }

        else {
                cout<<"file not found"<<endl;
        }

return 0;
}

Dani AI

Generated

The code posted by prints lines (using getline) and then makes an incorrect call to getchar(myfile,c). The file name used (example.rtf) is RTF, not plain text, so a raw word count there will include control words and braces. is correct to warn against testing eof() as the loop condition; is right that either reading words or scanning characters is the correct direction; and ’s suggestion to use isspace is useful but must be applied to characters read from the stream rather than as a bare loop condition.

Simplest, correct approach for plain-text files: read tokens with the stream extraction operator — it treats any whitespace as a delimiter and automatically stops at EOF. Example:

#include <fstream>
#include <iostream>
#include <string>

int main() {
    std::ifstream in("example.txt");
    if (!in) return 1;
    std::size_t words = 0;
    std::string token;
    while (in >> token) ++words;
    std::cout << "word count: " << words << '\n';
}

If tighter control is required (for example, to decide whether punctuation or hyphens count as part of a word), use a character-level state machine and std::isspace. Important: pass unsigned char to isspace to avoid undefined behavior with negative char values:

#include <fstream>
#include <iostream>
#include <cctype>

std::size_t count_words_charwise(std::ifstream &in) {
    char c;
    bool inWord = false;
    std::size_t words = 0;
    while (in.get(c)) {
        if (std::isspace(static_cast<unsigned char>(c))) {
            inWord = false;
        } else if (!inWord) {
            inWord = true;
            ++words;
        }
    }
    return words;
}

Other practical notes: don’t include <conio.h> or call nonstandard getchar() for file reads; use ifstream::get() or operator>>. Avoid counting spaces directly (multiple spaces, tabs, newlines, and punctuation make that unreliable). Since the original file is RTF, convert it to plain text or strip RTF control sequences before applying these counters for a meaningful word count.

Recommended Answers

All 5 Replies

You should not be doing while (!myfile.eof()) -- here's why (feof() and .eof() are identical)

After you've read all the lines in the loop, what do you expect getchar() to read?

You should not be doing while (!myfile.eof()) -- here's why (feof() and .eof() are identical)

After you've read all the lines in the loop, what do you expect getchar() to read?

Hi:

Thanks for ur reply.

Are you saying that i should use feof instead of eof ? I am not sure.

The other thing is I am not sure what I can do about that getchar. I am positive that what I have in my code is wrong. All I am able to see is that if there is a space, i should increment the counter by 1.

just keep counting every time it encounters a space

trying using isspace function I believe that calculates white spaces

while(isspace())
{
count++;
}

something like that.

Hi:

Thanks for ur reply.

Are you saying that i should use feof instead of eof ? I am not sure.

If they are identical, what do you think? You need to look in your text how to loop through a file.

The other thing is I am not sure what I can do about that getchar. I am positive that what I have in my code is wrong. All I am able to see is that if there is a space, i should increment the counter by 1.

Good, you know there is a problem. That's better than some others I've seen.
You need to think about what you are attempting to do. What designates the end of a word? What indicates the end of a line? Maybe in your loop instead of reading each line you could read each character looking for and counting these indicators.

See what you can do with that idea.

I'm confused. Your question states that you want to count the number or "words" in a file, but your program is counting the number of "lines" in the file. Which one are you trying to accomplish?

That getchar() is totally useless there because you've already gotten to the end of the file and then you try to read a character, but there's nothing left to read.

My suggestions would be the following:

a) If you want to truly count the number of words in the file then do something like:

- Read the file one character at a time and count the spaces between the words
- Or read the file one word at a time and count each word.

b) If you want to count the number of lines in the file then:

while (getline(myfile, line)) { size++; }

Don't check for eof at all, because you don't need to. It will stop at the end of the file automatically, but do check if the file is open. Maybe something like " if (myfile.fail()) { cerr << "Could not open file\n"; } ".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.