I'm trying to read a text file to find how many times a phrase/sentence(/substring?) occurs. I've done a real bodge job on it currently (see code below) but as you'll see, it relies on some rather clunky if statements.
I don't have access to the files I''ll be using it on at home, so I've used a file called big.txt and search for phrases like "and the" for the time being.
Ideally, I'd like to be able to search for "this error code 1" and it return the number of times it occurs. Any ideas on how I might get my code to work that way would be incredibly useful!
int fileSearch(string errorNameOne, string errorNameTwo, string textFile) { string output; //variable that will store word from text file ifstream inFile; inFile.open(textFile); //open the selected text file if (!inFile.is_open()) { cerr << "The file cannot be opened"; exit(1); } if (inFile.is_open()) { //Check to make sure the file has opened correctly while (!inFile.eof()) { //While the file is NOT at the end of the file inFile >> output; //Send the data from the file to "output" as a string if (output == errorNameOne) { //Check to look for first word of error code marker = 1; //If this word is present, set a marker to 1 } else if (marker == 1) { //If the marker is set to 1, if (output == errorNameTwo) { //and if the word matches the second error code... count++; //increse count } marker = 0; //either way, set marker to 0 again } } } inFile.close(); //Close the opened file return count; //Function returns count of error }