I am reading in a text file and basically, when a line has the user defined string, it prints the line and counts each time that word occurred. However, according to Notepad++, the word "the" should occur 3,781 times, but when I run the program I only get 3,404 times... and I believe it has to do with the string member function find().
/********************************************
* File: stringSearch.cpp
* Purpose:
* Write a program that asks for a user to
* enter the name of a file and a string
* to search for. The program will then
* display all lines the string occurs in
* and how many times it occurs.
**********************************************/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
/*the = 3404 times, should be 3,781*/
int main()
{
string infile, stringBuffer, stringBufCopy, userString;
size_t strFound;
int stringCount = 0;
int stringIt = 0;
cout << "Enter file name: ";
getline(cin, infile);
fstream file(infile, ios::in);
if(!file)
{
while(!file)
{
cout << "Invalid file entry!" << endl;
cout << "Re-enter file: ";
getline(cin, infile);
fstream file(infile, ios::in);
}
}
cout << "Enter string to search for: ";
getline(cin, userString);
while(!file.eof())
{
getline(file, stringBuffer, '.'); // Get line from file until a '.' occurs
stringBufCopy = stringBuffer;
strFound = stringBuffer.find(userString);
if(strFound != string::npos)
{
while(strFound != string::npos)
{
stringCount++;
cout << stringBuffer << endl;
strFound = stringBuffer.find(userString, strFound+1); // HERE maybe?
}
}
}
cout << "The string: \"" << userString << "\" was found " << stringCount << " times!" << endl;
file.close();
cin.clear();
cin.sync();
cin.get();
return 0;
}
Also, one more question... What does string::npos mean?
EDIT:: I know there are some redundancies and I will change and modify, but I have just been moving things around and adding and removing stuff, so for now, it's just getting it working properly, and will then take out redundancies and useless code.
Attached File(s)
-
taz.txt (256.71K)
Number of downloads: 20
This post has been edited by IngeniousHax: 27 June 2012 - 04:35 PM

New Topic/Question
Reply



MultiQuote








|