Main Page | Namespace List | Class Hierarchy | Alphabetical List | Class List | File List | Namespace Members | Class Members | File Members | Related Pages

mutable_universe.cpp


SourceForge.net Logo     CTTL on    
    SourceForge    
    Download    
    Latest    
    Documentation    
    Index    
    Library    
    News    
    CVS    
    Repository    
   Other    
   Links    

The following program implements one-pass algorithm to replace every occurence of a digit with its word equivalent:

// sample code: mutable_universe.cpp
// demonstrates cttl concept of mutable universe

//#define NDEBUG    // must appear before assert.h is included to stop assertions from being compiled 
//#define CTTL_TRACE_EVERYTHING

#include <iostream>
#include "cttl/cttl.h"

using namespace cttl;

struct digit_parser {

    static size_t rule_digit( edge<>& edge_ )
    {
        return (
            +(
                first( isdigit )
                &
                rule( digit_parser::event_digit )
            )
        ).match( edge_ );
    }

    static size_t event_digit( edge<>& edge_ )
    {
        // a single digit is found
        static const char* digits[] = {
            "zero;", "one;", "two;", "three;", "four;",
            "five;", "six;", "seven;", "eight;", "nine;"
        };

        size_t digit = edge_.first[ 0 ] - '0';
        assert( digit < ( sizeof( digits ) / sizeof( char ) ) );
        edge_.text( digits[ digit ] );
        return edge_.second.offset();
    }
};

int main(int argc, char* argv[])
{
    if ( argc == 1 ) {
        std::cout
            << "Usage: on the command line, enter a "
            << std::endl
            << "number to convert its digits to words,"
            << std::endl
            << "for example:"
            << std::endl
            << '\t'
            << argv[ 0 ]
            << " 123"
            << std::endl
            ;
        return 1;
    }

    input<> inp( argv[ 1 ] );
    edge<> universe( new_edge< std::string >( inp ) );
    if ( digit_parser::rule_digit( universe ) == std::string::npos ) {
        std::cout
            << "*** error *** no digits found at the beginning of the input"
            << std::endl
            ;
        return 1;
    }

    std::cout
        << inp.text()
        << std::endl
        ;
    return 0;
}
If argument "54321" is specified on the command line, the program prints the word equivalent of every digit:
five;four;three;two;one;

Similar program, number2words.cpp, converts integer numbers into their word equivalents.



Copyright © 1997-2006 Igor Kholodov mailto:cttl@users.sourceforge.net.

Permission to copy, use, modify, sell and distribute this document is granted provided this copyright notice appears in all copies. This document is provided "as is" without express or implied warranty, and with no claim as to its suitability for any purpose.


Generated on Thu Nov 2 17:44:54 2006 for Common Text Transformation Library by  doxygen 1.3.9.1