-2

I have been asked to develop program to count no. of lines and words in the file, this is my trial, my teacher said that I cant use >> operator for counting words and comparing but I could not handle it.

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

    int numberLines = 0;
    int numberWords = 0;

    void numberOfLines(){

    cout<<"number of lines is " << numberLines << endl;
    }
    void numberWords(){
    cout << "number of words is " << numberWords <<endl;
    }

    int main(){
    string line;
    char a = '';
    ifstream myfile("files.txt");

    if(myfile.is_open()){
    while(!myfile.eof()){
        getline(myfile,line);
        cout<< line << endl;
        numberLines++;
    }

    if ( a == ' '){
        NumberWords++;
    }

    }
    myfile.close();
    }
   numberOfLines();
   numberOfWords ();

   }
Reem Yehia
  • 1
  • 1
  • 1

1 Answers1

1

What you can do is add a 3rd argument to getline(). This lets it pull data from the stream until it hits a character. Doing getline(cin, line, ' ')takes all the data until the next and puts it into line. Your code might look like:

while(getline(inFile, line))
{
    ++numlines;
    stringstream lineStream(line);
    while(getline(lineStream, line, ' '))
    {
        ++numWords;
    }
}

The outer loop goes through the file and stores each line into line, then the inner goes through that line and counts each space. which correlates to a word.

Hawkeye5450
  • 672
  • 6
  • 18