string - Counting how many times certain words show up in a text file in C++ -
i trying make program 2 different text files. 1 of them contains actual text want analyze , other contains list of words. program supposed check when word list shows in text , count that. here (non working) code have far:
#include <iostream> #include <string> #include <fstream> using namespace std; int main () { string word1; string word2; int listhits = 0; ifstream data1 ("text.txt"); if ( ! data1 ) { cout << "could not open file: " << "text.txt" << endl; exit ( exit_failure ); } ifstream data2 ("list.txt"); if ( ! data2 ) { cout << "could not open file: " << "list.txt" << endl; exit ( exit_failure ); } while ( data1 >> word1 ) { while ( data2 >> word2 ) { if ( word1 == word2 ) { listhits++; } } } cout << "your text had " << listhits << " words list " << endl; system("pause"); return 0; }
if text.txt contains
here text. loaded program.
and list.txt contains
will a
the expected outcome 3. however, no matter in text files program gives me answer 0. have checked program manages read files having count times loops, , works.
thanks in advance
it seems me you're comparing first letter of first file entire second file, do:
while ( data1 >> word1 ) { while ( data2 >> word2 ) { // <---- after ends first time, never enter again if ( word1 == word2 ) { listhits++; } }
you need "reset" data2 after second loop finished starts read again beginning of file:
while ( data1 >> word1 ) { while ( data2 >> word2 ) { if ( word1 == word2 ) { listhits++; } } data2.seekg (0, data2.beg); }
Comments
Post a Comment