c++ - Reading data from a file with wrong count. What's best practice for reading in data? -


i have 4 sets of text files each containing different words.

noun.txt has 7 words article.txt has 5 words verb.txt has 6 words , preposition.txt has 5 words

in code below, inside second loop, array of counts keeps track of how many words i've read in , file. example. count[0] should 5 worlds is, count[1] has 8 words should 7. went check text file , didn't make mistake, has 7 words. problem how ifstream behaving ?

i've been told eof() not practice. what's best practice in industry in terms of reading in data accurately ? in other words there better 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 = 0; < 4; i++){         infile.open(file[i]);         if(!infile.is_open()){             cout << "error: unable 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 open or create file.\n";         system("pause");         exit(1);     }        outfile.close();     system("pause");     return 0; } 

the simple answer reading data this: always test after reading read operation successful. test not involve use of eof() (any book teaching use of eof() prior reading worthy burnt immediately).

the main loop reading file should this:

for (int j = 0; infile >> elements[j].partsofspeach[i]; ++j){     ++count[i]; } 

btw, although language called "c++" , not "++c", don't use post increment unless use result of expression: in cases doesn't matter matter , post-increment can significant slower pre-increment.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -