Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
For 2021 - online Python 3 training - see ((here)).

Our plans were to retire in summer 2020 and see the world, but Coronavirus has lead us into a lot of lockdown programming in Python 3 and PHP 7.
We can now offer tailored online training - small groups, real tutors - works really well for groups of 4 to 14 delegates. Anywhere in the world; course language English.

Please ask about private 'maintenance' training for Python 2, Tcl, Perl, PHP, Lua, etc.
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
Q908 - Object Orientation and General technical topics - Object Orientation: Design Patterns
  [485] North, Norther and Northest - PHP 5 Objects - (2005-11-04)
  [1224] Object Relation Mapping (ORM) - (2007-06-09)
  [2322] Looking for a practical standards course - (2009-08-05)
  [2741] What is a factory? - (2010-04-26)
  [2977] What is a factory method and why use one? - Example in Ruby - (2010-09-30)
  [3608] Design Patterns - what are they? Why use them? - (2012-02-12)
  [3716] Learning C++ - a design pattern for your first class - (2012-05-02)
  [3843] Caching Design Patterns - (2012-08-20)
  [4021] Spike solution, refactored and reusable, Python - Example - (2013-02-28)
  [4096] Perl design patterns example - (2013-05-20)
  [4098] Using object orientation for non-physical objects - (2013-05-22)
  [4325] Learning to program - what are algorithms and design patterns? - (2014-11-22)
  [4330] Java - factory method, encapsulation, hashmap example - (2014-11-27)
  [4356] Object factories in C++, Python, PHP and Perl - (2014-12-19)
  [4359] How to avoid too many recalculations within an object - (2014-12-21)
  [4377] Designing a base class and subclasses, and their extension, in C++ - (2015-01-01)
  [4396] Java Utility class - flexible replacement for array. Also cacheing in objects and multiple catch clauses example. - (2015-01-16)
  [4421] How healthy are the stars of stage and screen? - (2015-02-09)
  [4581] Thin application, thick objects - keep you main code simple. Example in Ruby - (2015-11-21)
  [4626] Singleton design pattern - examples and uses - (2016-01-20)
  [4663] Easy data to object mapping (csv and Python) - (2016-03-24)
  [4673] Separating detailed data code from the main application - Ruby example - (2016-05-16)

C239 - C and C based languages - Putting it all together
  [836] Build on what you already have with OO - (2006-08-17)
  [925] C++ - just beyond the basics. More you can do - (2006-11-14)
  [945] Code quality counts - (2006-11-26)
  [1181] Good Programming practise - where to initialise variables - (2007-05-09)
  [2646] Compile but do not run PHP - syntax check only - (2010-02-22)
  [2673] Multiple Inheritance in C++ - a complete example - (2010-03-12)
  [2674] Make and makefiles - a commented example to help you learn - (2010-03-12)
  [2851] Further C++ material - view new or old - (2010-07-04)
  [3067] Using C and C++ functions in the same program - how to do it - (2010-11-24)
  [3069] Strings, Garbage Collection and Variable Scope in C++ - (2010-11-25)
  [3252] C++ - unknown array size, unknown object type. Help! - (2011-04-17)
  [4326] Learning to program - comments, documentation and test code - (2014-11-22)
  [4374] Test driven development, and class design, from first principles (using C++) - (2014-12-30)
  [4559] When do I use the this keyword in C++? - (2015-10-29)

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

C235 - C and C based languages - I/O in C++
  [1675] Comparing Objects in C++ - (2008-06-13)
  [3124] C++ - putting the language elements together into a program - (2011-01-08)
  [3390] Printing objects in C++ - (2011-08-13)
  [3807] Reading (and writing) files in C++ - (2012-07-18)
  [4562] Left shift operator on an output stream object - C++ - (2015-10-30)
  [4563] Formatting and outputting your own classes in C++ - (2015-10-30)

C232 - C and C based languages - Defining and using classes in C++
  [1925] Introduction to Object Oriented Programming - (2008-12-06)
  [2577] Complete teaching example - C++, inheritance, polymorphism - (2010-01-15)
  [2578] Where are your objects stored in C++? - (2010-01-16)
  [2579] Creating, setting up and using objects in C++ - (2010-01-16)
  [3250] C++ - how we teach the language and the concepts behind the language - (2011-04-17)
  [3721] Naming blocks of code, structures and Object Orientation - efficient coding in manageable chunks - (2012-05-06)
  [3978] Teaching OO - how to avoid lots of window switching early on - (2013-01-17)
  [4129] Simple OO demonstration in C++, comparison to Python - (2013-07-01)
  [4372] Template / design pattern for C++ constructor and accessors - (2014-12-29)
  [4565] Allocation of memory for objects in C++ - Stack v Heap - (2015-10-31)


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
4759 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, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96 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., 2021: 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • 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 Oct 11 16:07:41 2020 • BUILD SYSTEM: JelliaJamb