user3251244
user3251244

Reputation: 17

Count words in each line of text file in c++

I open a txt file using argc, argv, and getline. I did that properly, but now I have to get the number of words per line (the number of lines is not known before) and I must output them in reverse. Meaning from the bottom line to the top line. Any help is appreciated. This code outputs the number of words in the file:

    #include <iostream>
    #include <fstream>
    #include <cstring>
    using namespace std;

    int main(int argc, char *argv[])
    {
        if(argc < 1){   
            cerr << "Usage: " << argv[0] << "filename.txt" << endl; 
        }

            ifstream ifile(argv[1]);
            if(ifile.fail()){
            cerr << "Could not open file." << endl;
            return 1;
            }

        int n;
        ifile >> n;
        cout << n;

        int numberOfWords = 0;  
        string line;
        for(int i = 0; i <=  n; i++){
            getline(ifile, line);
            cout << line << endl;
        }



        size_t i;

        if (isalpha(line[0])) {
            numberOfWords++;
        }

        for (i = 1; i < line.length(); i++) {
            if ((isalpha(line[i])) && (!isalpha(line[i-1]))) {
                numberOfWords++;
            }
        }



        cout<<"The number of words in the line is : "<<numberOfWords<<endl;

        return 0;
}

Upvotes: 1

Views: 5882

Answers (1)

David G
David G

Reputation: 96875

To find the number of words per line you would use std::getline() to iterate over each line and use std::stringstream to extract each chunk of whitespace-separated input. Then you would iterate over each chunk of input and check to see if each character is alphabetic:

int numberOfWords = 0;

for (std::string line, word; std::getline(ifile, line); )
{
    std::istringstream iss(line);

    while (iss >> word)
    {
        bool alpha = true;

        for (char c : word)
            if (!std::isalpha(c)) alpha = false;

        if (alpha) ++numberOfWords;
    }
    std::cout << "Number of words on this line: " << numberOfWords << std::endl;
    numberOfWords = 0;
}

Upvotes: 1

Related Questions