Search code examples
c++filestreamsequential

C++: Finding the chapter of a book


I have a rather large text file, and want to have a C++ program that scans through it and returns the section of the chapter that I want. For example, let's say that the file is called "MyTales.txt", and the contents of it are

MYTALE by Me (classifying what book it is)
CHAPTER ONE
Part 1: The Start

Where Part 1 (in its entirety) is the section to be returned.

As a basic template, here's what I thought of so far:

#include<iostream>
#include<fstream>

ifstream in;
ofstream out;

string book, chapter, part;

int main() {
 cout << "Please enter the part to locate:\nBook: ";
 cin >> book;
 cout << "Chapter: ";
 cin >> chapter;
 cout << "Part: ";
 cin >> part;

 in.open("MyTales.txt");
 while (in >> data) {
  // where data is assigned
 }

 out.open("BookParts.txt");
 out << data;

 in.close();
 out.close();
}

I'm just not sure how to assign "data" properly. I've tinkered w/ some string functions and other things, but nothing seems to work out. Any help is greatly appreciated!


Solution

  • The first problem would be to generate the title of the chapter from its numerical value. Once the name is obtained, ignore the input line-wise including the chapter name. Then read the input until you encounter a line beginning with "CHAPTER" or the end of the Input. Finally output everything you have read.