0

I have a simple program that reads how many words are in a file. For the purpose of this program a word is anything not separated by a space. My problem is that ifstream is reading the string character twice for my files. I don't understand this?

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

int main() {

    ifstream infile;
    string str1;
    string filename;
    int count;

    cout << "enter a file name: ";
    cin >> filename;

    while (filename != "quit") {
        infile.open(filename.c_str());
        if (!infile) {
            cout << "Couldn't open file." << endl;
        } else {
            count = 0;
            while (infile) {
                infile >> str1;
                cout << str1 << endl;
                count++;
            }
            infile.close(); 
            cout << count << endl;
        }
        cout << "enter a filename: ";
        cin >> filename;

    }
}

Here is an example file text:

This &%file              should!!,...



have exactly 7 words.

Output:

enter a file name: file1
This
&%file
should!!,...
have
exactly
7
words.
words.
8
O'Neil
  • 3,790
  • 4
  • 16
  • 30
  • Exact duplicate. – user202729 Jan 20 '18 at 07:29
  • 2
    The duplicate has a somewhat confusing title since no calls to `eof()` are explicitly done in the code, but reading the answer in the duplicate shows the issue. More succinctly -- `while (infile >> str1)` is not the same as `while (infile) { infile >> str; ...` – PaulMcKenzie Jan 20 '18 at 07:39

0 Answers0