Reading data from a file with wrong count. What's best practice for
reading in data?
I have four sets of text files each containing different words.
noun.txt has 7 words Article.txt has 5 words verb.txt has 6 words and
Preposition.txt has 5 words
In the code below, inside my second for loop, an array of counts keeps
track of how many words i've read in and from what file. so for example.
count[0] should be 5 worlds which it is, but count[1] has 8 words but
should be 7. I went back to check the text file and i didn't make a
mistake, it has 7 words. Is this a problem with how ifstream is behaving ?
I've also been told eof() is not good practice. What's best practice in
industry in terms of reading in data accurately ? In other words is there
something better i can use besides !infile.eof() ?
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <cctype>
#include <array> // std::array
using namespace std;
const int MAX_WORDS = 100;
class Cwords{
public:
std::array<string,4> partsOfSpeech;
};
int main()
{
Cwords elements[MAX_WORDS];
int count[4] = {0,0,0,0};
ifstream infile;
string file[4] = {"Article.txt",
"Noun.txt",
"Preposition.txt",
"verb.txt"};
for(int i = 0; i < 4; i++){
infile.open(file[i]);
if(!infile.is_open()){
cout << "ERROR: Unable to open file!\n";
system("PAUSE");
exit(1);
}
for(int j = 0;!infile.eof();j++){
infile >> elements[j].partsOfSpeech[i];
count[i]++;
}
infile.close();
}
ofstream outfile;
outfile.open("paper.txt");
if(!outfile.is_open()){
cout << "ERROR: Unable to open or create file.\n";
system("PAUSE");
exit(1);
}
outfile.close();
system("PAUSE");
return 0;
}