Here is the problem(this is for a intro to C/C++ class):
Write a program that asks the user for a file name and a string to search for. The program should search the file for every occurrence of a specified string. When the string is found, the line that contains it should be diplayed. After all the occurrences have been located, the program should report the number of times the string appeared in the file.
I created a text file with the following text:
one two three four five
two three four five six
three four five six seven
four five six seven eight
five six seven eight nine
six seven eight nine ten
The problem I'm having right now is trying to search for the string within the file. I know you can use strstr to search for a string within a string, but I'm not sure how to search within the file. What I have so far is below. Any help to point me in the right direction would be great.
CODE
// Chapter 12, Program Challenge 6 - string search
// This program will search for a specific string (based on user input)
// in a file and then return all lines that include that string.
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
int main()
{
const int SIZE = 31; // constant for size of character string
char stringSearch[SIZE]; // used to search for the string in the file
char fileName[SIZE]; // to hold the file name
ifstream inputFile; // input file
int counter = 0; // counter for counting number of string occurences
char *stringPtr; // points to the string
// Prompt user to select a string to search from the file
cout << "Enter a word or string of words to search for: ";
cin.getline(stringSearch, SIZE);
// Get the input file name
cout << "Enter the name of a file that you would\n";
cout << "like to search for a string within: ";
cin >> fileName;
// Open the file for input.
inputFile.open(fileName);
if(!inputFile)
{
cout << "Cannot open " << fileName << endl;
system("pause");
return 0;
}
// Search file for user-input string
while(!inputFile.eof())
{
inputFile.getline(stringSearch, SIZE);
cout << stringSearch;
cout << endl;
}
cout << endl;
// Close the files.
inputFile.close();
system("pause");
return 0;
}