file searching problem
-
I'm trying to search an input file for all occurences of a user specified string and return how many times the word was found and read that into an output file. For some reason the the value of the string changes to every word in the text file at runtime. What am I doing wrong?
#include #include #include #include using namespace std; int main(void) { string filename; cout << "Please enter the name of the file: " ; cin >> filename; string search; cout << "Please enter the word to search for"; cin >> search; ifstream fin(filename.c_str()); while (fin.fail()) { cout << "invalid file name"<< endl; cout << endl << "Please enter the name of the file: "; cin >> filename; fin.clear(); fin.open( filename.c_str() ); } int count=0; while (fin >> (search)) { count++; } ofstream fout("output.txt"); fout << "The number of times "<< search <<" was found is "<< count << endl; system ("pause"); return 0; }
BINARY -
I'm trying to search an input file for all occurences of a user specified string and return how many times the word was found and read that into an output file. For some reason the the value of the string changes to every word in the text file at runtime. What am I doing wrong?
#include #include #include #include using namespace std; int main(void) { string filename; cout << "Please enter the name of the file: " ; cin >> filename; string search; cout << "Please enter the word to search for"; cin >> search; ifstream fin(filename.c_str()); while (fin.fail()) { cout << "invalid file name"<< endl; cout << endl << "Please enter the name of the file: "; cin >> filename; fin.clear(); fin.open( filename.c_str() ); } int count=0; while (fin >> (search)) { count++; } ofstream fout("output.txt"); fout << "The number of times "<< search <<" was found is "<< count << endl; system ("pause"); return 0; }
BINARYBinary, Your problem exists here:
while (fin >> (search))
{
count++;
}You are reading a "word" from your file and storing it in the
string
that you declared to hold your search term. Instead, reuse thefilename
variable or declare a new one.while (fin >> (filename))
{
// If the "word" in filename equals the
// word in search, then
count++;
}"we must lose precision to make significant statements about complex systems." -deKorvin on uncertainty -- modified at 16:04 Wednesday 23rd November, 2005