File content search.
Write a program that reads a file named example.txt line by line and searches for a specific string provided by the user. The program should print all lines from the file that contain the specified string. If the string is not found in any line, the program should output an appropriate message.
Example
example.txt:
This is the first line of the file.
The quick brown fox jumps over the lazy dog.
Another line with some random text.
Searching through this file should be fun.
The final line is here.
Program:
Enter the string to search for: line
This is the first line of the file.
Another line with some random text.
The final line is here.
Hint
- Use
std::getlineto read the file line by line. - Use
std::string::findto search for the substring within each line.
Answer
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream inFile("example.txt");
if (!inFile) {
std::cout << "Error: Could not open the file." << std::endl;
return 1;
}
std::string searchString;
std::cout << "Enter the string to search for: ";
std::getline(std::cin, searchString);
std::string line;
bool found = false;
while (std::getline(inFile, line)) {
if (line.find(searchString) != std::string::npos) {
std::cout << line << std::endl;
found = true;
}
}
if (!found) {
std::cout << "No lines containing the string \"" << searchString << "\" were found." << std::endl;
}
inFile.close();
return 0;
}