C++: Read File and Search for Line
by matt392 in Circuits > Software
9 Views, 0 Favorites, 0 Comments
C++: Read File and Search for Line


C++ program that reads in Shakespeare's "Hamlet" as a text file. Then it searches for the line "The undiscovered country from whose bourn".
// Read file and search for text
// Used Code::Blocks IDE with GCC compiler
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{ // start main function
// Declare variables
// File goes here
fstream InputFile;
// Each line goes in this variable
string LineFromStarFile;
// Open the file
InputFile.open("hamlet.txt");
// Search for particular line in file
while (getline(InputFile, LineFromStarFile))
{
if (LineFromStarFile=="The undiscovered country from whose bourn")
cout << LineFromStarFile << endl;
} // end while loop
// Close the file
InputFile.close();
return 0;
} // end main function
Supplies



- Desktop or laptop computer.
- C++ compiler like GCC.
- Code::Blocks C++ IDE or similar IDE.
C++ Source Code and Text File With Hamlet


// Read file and search for text
// Used Code::Blocks IDE with GCC compiler
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{ // start main function
// Declare variables
// File goes here
fstream InputFile;
// Each line goes in this variable
string LineFromStarFile;
// Open the file
InputFile.open("hamlet.txt");
// Search for particular line in file
while (getline(InputFile, LineFromStarFile))
{
if (LineFromStarFile=="The undiscovered country from whose bourn")
cout << LineFromStarFile << endl;
} // end while loop
// Close the file
InputFile.close();
return 0;
} // end main function