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

undiscovered2.jpg
hamletquote.jpg

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

desktopcomputer.png
C++Logo.jpg
codeblocks.jpg
  1. Desktop or laptop computer.
  2. C++ compiler like GCC.
  3. Code::Blocks C++ IDE or similar IDE.

C++ Source Code and Text File With Hamlet

hamletquote.jpg
undiscovered.jpg
// 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