Home Accessibility Courses Diary The Mouth Facebook Resources Site Map About Us Contact
Reading files, and using factories to create vectors of objects from the data in C++

On our C++ courses, we concentrate on objects and object design. But we also take a wider look at topics such as references and templates that go to making the complete language, with sections covering changes to things like file handling from the underlying C language.

I've just added a new example to our web site, developed during the last few days as a "show you how" on our course.

Scenario ... I have a file which comprises a number of records, and I want to read each of those records in, in turn, turn each into an object which I can then manipulate. This may be a very familiar scenario for anyone who's used to processing data.

The first sample program - [here] - uses a static C++ method (using a factory design pattern) to handle the data flowing in from the file. The factory method is rather like a utility function that resides in the class for the object type we're creating (in this case a Train). It contains code that's logically associated with setting up Trains (such as reaidng standard file formats of Train information), but it doesn't run on any pre-existing Train objects. And - although it may return a Train object (in the way a constructor always does, it may not ... our example returns a NULL if there's no (more) data available.

Here's the factory:

  Train* Train::factory() {
    char trainline[256];
    if (! datasource) { // Only on the first call do you open the file
      datasource = new ifstream("trains.txt");
      }
    // read the (next) line from the file
    datasource->getline(trainline,256);
    if (datasource->eof()) {
      return NULL;
      }
    return new Train(trainline);
    }


We're passing a complete (String) record to the constructor, you'll notice. For in this case, we can be sure that every string represents a good record. Within the constructror, we're separating out the individual fields in our space delimied line ... dropping \0 (null) characters in to conveniently split the string, then sucking out the various pieces we want:

  Train::Train(char * source) {
    int starts[4];
    int k=0;
    int param=0;
  
    while (source[k] != '\0') {
      if (source[k] == ' ') {
        source[k] = '\0';
        starts[param++] = k+1;
      }
      k++;
      if (param > 3) break;
    }
  
    this->ncars = atoi(&source[starts[2]]);
    this->spv = atoi(&source[starts[1]]);
    }





In the first example, we've only allowed for a specific and limited number of Train objects in the array in our main program. But it's rarely the case that we know how may are needed, so we've switched on to using a vector in the second example - see [here].

A vector is a collection (a linked list) which unlike an array doesn't need to occupy sequential memory locations - so it can be expanded later. In fact, we start off with it being zero in size (capacity):
  vector<Train *> *service = new vector<Train *>(0);

We can add Train object onto the end of it using the push_back method:
  service->push_back(current);

and we can then reference elements that we need using the at method:
  cout << service->at(k)->getcapacity() << endl;




In our final example, we've switched so that the program runs on data that's brought in from a file named on the command line. That final example is [here].

As there's more chance of the user getting things wrong, we've added in checks for command line usage:
  if (argc != 2) {
    cerr << "Usage: " << argv[0] << " filename" << endl;
    return 1;
    }

and we're also checking that our file open is working properly:
  datasource = new ifstream(source);
    if (! datasource->good()) {
      cerr << "Unable to open data file" << endl;
      return NULL;
      }


The data file that I used in running / testing these programs is [here]

We offer a range of C and C++ courses, suitable for the newcomer to programming (the longer courses) and the programmer converting to a new language (shorter ones). See C and C++ course details.

(written 2012-07-21, updated 2012-08-11)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
C232 - C and C based languages - Defining and using classes in C++
  [4129] Simple OO demonstration in C++, comparison to Python - (2013-07-01)
  [3978] Teaching OO - how to avoid lots of window switching early on - (2013-01-17)
  [3721] Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks - (2012-05-06)
  [3716] Learning C++ - a design pattern for your first class - (2012-05-02)
  [3250] C++ - how we teach the language and the concepts behind the language - (2011-04-17)
  [2579] Creating, setting up and using objects in C++ - (2010-01-16)
  [2578] Where are your objects stored in C++? - (2010-01-16)
  [2577] Complete teaching example - C++, inheritance, polymorphism - (2010-01-15)
  [1925] Introduction to Object Oriented Programming - (2008-12-06)

C235 - C and C based languages - I/O in C++
  [3807] Reading (and writing) files in C++ - (2012-07-18)
  [3390] Printing objects in C++ - (2011-08-13)
  [3252] C++ - unknown array size, unknown object type. Help! - (2011-04-17)
  [3124] C++ - putting the language elements together into a program - (2011-01-08)
  [1675] Comparing Objects in C++ - (2008-06-13)
  [1478] Some new C programming examples - files, structs, unions etc - (2007-12-19)

C238 - C and C based languages - Templates
  [3982] Using a vector within an object - C++ - (2013-01-19)
  [3509] Operator Overloading, Exceptions, Pointers, References and Templates in C++ - new examples from our courses - (2011-11-06)
  [3388] Templates in C++ - defining a family pattern of methods / functions - (2011-08-12)
  [3245] Collections in C and C++ - arrays, vectors and heap memory blocks - (2011-04-12)

C239 - C and C based languages - Putting it all together
  [3069] Strings, Garbage Collection and Variable Scope in C++ - (2010-11-25)
  [3067] Using C and C++ functions in the same program - how to do it - (2010-11-24)
  [2851] Further C++ material - view new or old - (2010-07-04)
  [2674] Make and makefiles - a commented example to help you learn - (2010-03-12)
  [2673] Multiple Inheritance in C++ - a complete example - (2010-03-12)
  [2646] Compile but do not run PHP - syntax check only - (2010-02-22)
  [1181] Good Programming practise - where to initialise variables - (2007-05-09)
  [945] Code quality counts - (2006-11-26)
  [925] C++ - just beyond the basics. More you can do - (2006-11-14)
  [836] Build on what you already have with OO - (2006-08-17)

Q908 - Object Orientation and General technical topics - Object Orientation: Design Patterns
  [4098] Using object orientation for non-physical objects - (2013-05-22)
  [4096] Perl design patterns example - (2013-05-20)
  [4021] Spike solution, refactored and reusable, Python - Example - (2013-02-28)
  [3843] Caching Design Patterns - (2012-08-20)
  [3608] Design Patterns - what are they? Why use them? - (2012-02-12)
  [2977] What is a factory method and why use one? - Example in Ruby - (2010-09-30)
  [2741] What is a factory? - (2010-04-26)
  [2322] Looking for a practical standards course - (2009-08-05)
  [1224] Object Relation Mapping (ORM) - (2007-06-09)
  [485] North, Norther and Northest - PHP 5 Objects - (2005-11-04)


Back to
Dwarf Exception Unwind Info
Previous and next
or
Horse's mouth home
Forward to
Associated Classes - using objects of one class within another
Some other Articles
Returning guests - a sign of a good product. Cream teas and hotel rooms.
Injection Attacks - PHP, SQL, HTML, Javascript - and how to neutralise them
The Melksham News - July 2012 - Part 1, Campus and Chamber of Commerce
Associated Classes - using objects of one class within another
Reading files, and using factories to create vectors of objects from the data in C++
Dwarf Exception Unwind Info
Can you put names to faces?
2011 Census results - initial figures for Wiltshire.
Scenes from commuting by train
4280 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/3810_Rea ... in-C-.html • PAGE BUILT: Sun Mar 30 15:20:58 2014 • BUILD SYSTEM: WomanWithCat