0

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!

Jørgen R
  • 9,179
  • 7
  • 36
  • 56
T145
  • 1,118
  • 1
  • 9
  • 28
  • 1
    http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong – Mat Oct 10 '14 at 21:40
  • 1
    A text file is a *very* unstructured file format. All you know is where a line begins and ends. The exact semantics of a line are not fixed at all, just a blurb of characters. You'll have to make your own rules. Something draconian like the first line of a chapter contains the number of lines in the heading and the text of the chapter. XML is a draconian format. Anything goes, as long as whatever program generates the text file agrees with your rules. – Hans Passant Oct 10 '14 at 21:58
  • Well, I'm not saying that's not what I want to do, it's just that I'm dealing w/ quite a large amount of data that happens to have been stored in text files, so flipping it all over to a different format really wouldn't be an option at this point. – T145 Oct 10 '14 at 22:00

1 Answers1

0

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.

Codor
  • 16,805
  • 9
  • 30
  • 51
  • How would I ignore the input? My first implementation used a compact if statement to determine the line given, then I used a `getline(in, data);` statement. – T145 Oct 10 '14 at 21:48
  • By "ignoring" I mean reading a line, but not storing the obtained line. – Codor Oct 10 '14 at 21:53