1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Programming Tutorial - C++ Strings

By , About.com Guide

9 of 10

A Small Text Processing example

Example 8 is a small working application that reads in a file, searches it for urls, builds a list of them which is then sorted and printed out. It uses the vector class and sort algorithm from the STL and the std::ifstream class.

Download Example 8

The template vector list holds all the extracted links.

vector<string> links;
The vector<string> is template notation to show that the vector class will hold strings. All of the functionality is in the class textfile which is instantiated with the path and name of the file to load in.

The design means that when the constructor has finished, the file will have been processed and the list of url will be complete. There are two main processes used.

  1. Read in the file into a string.
  2. Process the string into a list. [/uol]

    Reading the File

    This uses the ifstream class to open the file. It then calls the seekg() function to move a file pointer to end of the file, calls tellg() to report its position i.e. indicate how big the file is. This is passed into reserve() so that the string starts as big as it needs to be. I've used a simple loop to read the file contents into the text string line by line. If you are searching a file, line breaks can be a real pain to deal with. Just in case any slipped through, the removecrlf() method converts them to spaces.

    On the next page - Processing the file

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2009 About.com, a part of The New York Times Company.

All rights reserved.