0

This is what I have so far... The point of this program is to display the number of words in a file, and also get the number of letters in the number of words of that same file.

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

    using namespace std;

    int main()
    {
      int numberOfWords = 0, i = 0;
      char letters = 0;
      string line;

      ifstream myFile;
      myFile.open("text.txt");

     //I got this to work, it displays the number of words in the file
    if (myFile.is_open())
    {
        while (!myFile.eof())
    {
        myFile >> line;
        i++;
    }
    numberOfWords = i;

    //this is where I'm having trouble. I can't get this code to work for it to display the number of letters in the file.
    while (!myFile.eof())
    {
        //cout << line << endl;
        letters = line.length();
        letters++;
    }
}
        myFile.close();

        cout << "There are " << numberOfWords << " words in the textfile\n"
            << "There are " << letters << " letters in those " <<       numberOfWords << " words\n";

        cin.get();

        return 0;

}

S.Henry
  • 5
  • 3
  • 4
    Have a look [here](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) please, before going further. – πάντα ῥεῖ Mar 08 '17 at 14:39
  • `!myFile.eof()` was already true when you come to your second loop. You have at least to call `myFile.clear()` and `myfile.seek(0)` to start reading from the file again. – πάντα ῥεῖ Mar 08 '17 at 14:40
  • Why do you need second while? You can get number of letters calculation in the same loop. `while (myfile >> line) { ++numberOfWords; letters += line.length(); }` – JustRufus Mar 08 '17 at 14:45
  • Number of characters of number of words? You title doesn't match. – eerorika Mar 08 '17 at 15:09
  • I tried that but it gives me the wrong number of letters... – S.Henry Mar 08 '17 at 15:13

1 Answers1

0

You are doing it wrong.

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

using namespace std;

int main()
{
  int numberOfWords = 0, i = 0;
  int letters = 0;
  string line;

  ifstream myFile;
  myFile.open("text.txt");

 //I got this to work, it displays the number of words in the file
if (myFile.is_open())
{
    while (!myFile.eof())
    {
        myFile >> line;
        letters += line.length();
        //letters++;
        i++;

    }
numberOfWords = i;

//this is where I'm having trouble. I can't get this code to work for it to display the number of letters in the file.
//while (!myFile.eof())
//{
    //cout << line << endl;

//}
}
myFile.close();

    cout << "There are " << numberOfWords << " words in the textfile\n"
        << "There are " << letters << " letters in those " <<       numberOfWords << " words\n";

    cin.get();

    return 0;
}

Just count the number of letters of the words as you go on traversing the line

Sniper
  • 1,341
  • 1
  • 11
  • 25