C++ program that searches a file for every occurrence of a specified string
String Search
Write a C++ 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 displayed. After all the occurrences have
been located, the program should report the number of times the string appeared in
the file.
Answer:
// String Search
#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
// Constant for array size
const int SIZE = 81;
int main()
{
ifstream file; // File stream object
char name[SIZE]; // To hold the file name
char inputLine[SIZE]; // To hold a line of input
char search[SIZE]; // The string to search for
int found = 0; // Counter
// Get the file name.
cout << "Enter the file name: ";
cin.getline(name, SIZE);
// Open the file.
file.open(name);
// Test for errors.
if (!file)
{
// There was an error so display an error
// message and end the program.
cout << "Error opening " << name << endl;
exit(EXIT_FAILURE);
}
// Get the string to search for.
cout << "Enter string to search for: ";
cin.getline(search, 81);
// Search for the string.
while (!file.eof())
{
// Get a line of input.
file.getline(inputLine, SIZE, '\n');
// Determine whether the line contains
// the string.
if (strstr(inputLine, search) != 0)
{
// Yes it did. Display the line.
cout << inputLine << endl;
// Update the counter.
found++;
}
}
// Close the file.
file.close();
// Display the number of times the string
// was found in the file.
cout << "\n\"" << search << "\" was found "
<< found << " times.\n";
return 0;
}
Leave a reply