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