pgnlib: a c++ library for PGN chess games

Tutorial - 3


3. "Hello World!"

Let's say we have pgnlib installed on our machine and a sample.pgn file filled with games.
The first thing we surely want to do is to parse the file and fill a GameCollection object with the games found.
Our first example, a sort of "hello world" program for pgnlib, does little more than that.

#include <PGNGameCollection.h> 
#include <fstream>

int main()
{
    try
    {
        ifstream pgnfile("./sample.pgn");

        pgn::GameCollection games;

        // collecting games from file
        pgnfile >> games;

        // counting the games
        cout << "The sample.pgn file contains " << games.size() 
             << " games." << endl;
    }
    catch (exception &e)
    {
        cerr << "exception: " << e.what() << endl;
        return -1;
    }
    return 0;
}

Note that I put all the code inside a try-catch block because pgnlib rely on c++ exceptions to manage run time errors.

For instance if your sample.pgn file turns out to be corrupt you will get an exception thrown by the pgnlib parser.

Then we define an input file stream for our sample pgn (pgnfile) and an object of class GameCollection (games).

The latter is a container for Game objects: we want the contents of sample.pgn to fill this GameCollection so that we can then manipulate
the games through the GameCollection and Game class interface.

This is accomplished by the simple statement

pgnfile >> games

Now we can query the GameCollection to know how many games it consists of: the method GameCollection::size() is used for this purpose.

[2. The pgnlib classes] [Home] [4. Processing games]

SourceForge.net Logo Valid HTML 4.01!