Wednesday, July 29, 2015

void* universal pointer

void* also known as universal pointer or generic pointer can be used to hold the address of any type assigned to it.

void* universal pointer can also be used as a function argument.

Below example transferValues function declares two void* arguments.

Instead of writing two different functions for int and double types only one transferValues function with void* arguments can be used.

void* seems to be usable but there are type-safety related problems with void pointer.

With a suitable casting operation existing void* universal pointer can be converted to an appropriate type.

Because a void pointer can not be dereferenced directly, static_cast can be used to cast from void* to another type.

Following error message is generated by the compiler if a void* is dereferenced before casting to an appropriate type.

'void*' is not a pointer-to-object type
           

Example void pointer project compiled with : g++ (Ubuntu 4.9.2-10ubuntu13) 4.9.2


#include <iostream>
using namespace std;

enum ParamType
{
    intType,
    doubleType
};

void transferValues( void* from, void* to, int size, ParamType pType)
{

    if( pType == intType )
    {
         for (int i= 0; i<size; i++)
         {
             static_cast<int*>(to)[i] = static_cast<int*>(from)[i];
         }
    }
    else if( pType == doubleType )
    {
         for (int i= 0; i<size; i++)
         {
             static_cast<double*>(to)[i] = static_cast<double*>(from)[i];
         }
    }
}

int main()
{

    int val = 5;
    void* vPtr = &val;
    // below line generates compile error
    // cout << *vPtr;
    int* newVal = static_cast<int*>(vPtr);
    cout << *newVal << endl;

    double dVal = 5.2;
    vPtr = &dVal;
    double* newDVal = static_cast<double*>(vPtr);
    cout << *newDVal << endl;

    char cVal = 'c';
    vPtr = &cVal;
    char* newCVal = static_cast<char*>(vPtr);
    cout << *newCVal;

    cout << endl << endl;

    int a[5] = { 1, 2, 1, 1, 1 };
    int b[5];

    cout << "Elements of array a = ";
    for( int i = 0; i<5; i++ )
        cout << a[i] << " ";

    cout << endl << "Elements of array b before casting = ";
    for( int i = 0; i<5; i++ )
        cout << b[i] << " ";

    transferValues( a, b, 5, intType );
    cout << endl << "Elements of array b after casting = ";
    for( int i = 0; i<5; i++ )
        cout <<  b[i] << " ";

    double c[5] = { 2.3, 3.3, 4.3, 5.3, 6.3 };
    double d[5];

    cout << endl << endl << "Elements of array c = ";
    for( int i = 0; i<5; i++ )
        cout << c[i] << " ";

    cout << endl <<"Elements of array d before casting = ";
    for( int i = 0; i<5; i++ )
        cout << d[i] << " ";

    transferValues( c, d, 5, doubleType );
    cout << endl << "Elements of array d after casting = ";
    for( int i = 0; i<5; i++ )
        cout << d[i] << " ";

    cout << endl << endl;

    return 0;
}

After running the program following terminal output displayed.


Saturday, July 25, 2015

toLower and toUpper Character Functions in C++ without using string.h and ctype.h

string.h and ctype.h libraries have got functions defined for converting characters from upper case to lower case and vice versa.

Sample functions below achieves in a c program following requirements :

1- convert a given character from lower case to upper case character
2- convert a given character from upper case to lower case character
3- convert a given whole string from lower case to upper case string
4- convert a given whole string from upper case to lower case string

with the following constraints :

1- All letters are English alphabet letters
2- There is no space in the input
3- Only character input is assumed


Main rule to remember when converting case for letters is :

Upper case character = Lower case character - ('a'-'A');
Lower case character = Upper case character + ('a'-'A');

Here the difference ('a'-'A') corresponds to 32.


#include <stdio.h>

char charToLower(const char& cUpper)
{
    if(cUpper>='A' && cUpper<='Z')
        return cUpper+('a'-'A');
    else
        return cUpper;
}

char charToUpper(const char& cLower)
{
    if(cLower>='a' && cLower<='z')
        return cLower-('a'-'A');
    else
        return cLower;
}

char* strToLower( char strUpper[] )
{
    int i = 0;
    while(strUpper[i] != '\0')
        i++;

    char* strLower = new char[i];
    i=0;
    while( strUpper[i] != '\0' )
    {
        if(strUpper[i]>='A' && strUpper[i]<='Z')
            strLower[i] = strUpper[i]+('a'-'A');
        i++;
    }
    return strLower;
}

char* strToUpper( char strLower[] )
{
    int i=0;
    while(strLower[i] != '\0')
        i++;

    char* strUpper = new char[i];
    i=0;
    while( strLower[i] != '\0' )
    {
        if( strLower[i]>='a' && strLower[i]<='z')
            strUpper[i] = strLower[i]-('a'-'A');
        i++;
    }
    return strUpper;
}

int main()
{
    char upperCaseChar = 'C';
    char lowerCaseChar = charToLower(upperCaseChar);
    printf("Upper Case Character : %c \n", upperCaseChar);
    printf("Lower Case Character : %c \n\n", lowerCaseChar);

    char lowerTestChar = 'f';
    char upperTestChar = charToUpper(lowerTestChar);
    printf("Lower Case Character : %c \n", lowerTestChar);
    printf("Upper Case Character : %c \n\n", upperTestChar);

    char upperCaseString[] = "TRKSH";
    char* lowerCaseString = strToLower(upperCaseString);
    printf("Upper Case String : %s \n", upperCaseString);
    printf("Lower Case String : %s \n\n", lowerCaseString);
    delete[] lowerCaseString;

    char lowerCaseTestString[] = "trksh";
    char* upperCaseTestString = strToUpper(lowerCaseTestString);
    printf("Lower Case String : %s \n", lowerCaseTestString);
    printf("Upper Case String : %s \n\n", upperCaseTestString);
    delete[] upperCaseTestString;

    return 0;
}

After running the program following terminal output displayed.


Friday, July 24, 2015

Palindrome String Check in C++ without using string.h

Palindrome check for a given string is very popular starting exercise for new programmers. It has got many implementations in Java and C++. Most of the implementations use existing String class in Java or string.h header in C++.

Following string palindrome check function in c++ without using string.h works with the constraints :

- strings that do not contain any space
- strings just contain English alphabet characters
- strings with more than 3 characters


#include <stdio.h>

int isPalindrome( const char* arr )
{
    int stringLength = 0;
    int index = 0;
    while(arr[index]!='\0')
    {
        ++stringLength;
        ++index;
    }

    if( stringLength >= 0 && stringLength <=2 )
        return 0;

    for(int i = 0; i<stringLength/2; i++)
    {
        if(arr[i] != arr[stringLength-1-i])
            return 0;
    }

    return 1;
}

int main()
{
    const char* stringToCheck1 = "aba";
    int res = isPalindrome(stringToCheck1);
    if(res)
        printf("%s is palindrome\n", stringToCheck1);
    else
        printf("%s is not palindrome\n",stringToCheck1);

    const char* stringToCheck2 = "abba";
    res = isPalindrome(stringToCheck2);
    if(res)
        printf("%s is palindrome\n",stringToCheck2);
    else
        printf("%s is not palindrome\n",stringToCheck2);

    const char* stringToCheck3 = "abccccba";
    res = isPalindrome(stringToCheck3);
    if(res)
        printf("%s is palindrome\n",stringToCheck3);
    else
        printf("%s is not palindrome\n",stringToCheck3);

    const char* stringToCheck4 = "abcc111211ccba";
    res = isPalindrome(stringToCheck4);
    if(res)
        printf("%s is palindrome\n",stringToCheck4);
    else
        printf("%s is not palindrome\n",stringToCheck4);

    const char* stringToCheck5 = "";
    res = isPalindrome(stringToCheck5);
    if(res)
        printf("%s is palindrome\n",stringToCheck5);
    else
        printf("%s is not palindrome\n",stringToCheck5);

    return 0;
}

After executing above main function following terminal output is produced.


Thursday, July 23, 2015

Iterative and Recursive Factorial Functions in C++

Factorial function is defined as a function which multiplies a given number by every number below it until 1.

For example 5!= 5*4*3*2*1=120.

In C++, factorial function can be implemented in an iterative or recursive way.

For big numbers, return value of factorial functions are declared as unsigned long long.


#include <iostream>
using namespace std;

unsigned long long iterativeFactorial( const unsigned int& value )
{
    unsigned long long result=1;
    unsigned long long i=1;
    while(i<=value)
    {
        result *= i++;
    }

    return result;
}

unsigned long long recursiveFactorial( const unsigned int& value )
{
    if( value == 1 || value == 0 )
        return 1;
    return value*recursiveFactorial(value-1);
}

int main()
{
    const unsigned long value = 20;
    unsigned long long iterativeFactorialResult = iterativeFactorial( value );
    cout << "Iterative Factorial Result : "<< iterativeFactorialResult << endl;

    unsigned long long recursiveFactorialResult = recursiveFactorial( value );
    cout << "Recursive Factorial Result : "<< recursiveFactorialResult << endl;

    return 0;
}

Both factorial functions in C++ source code were tested with the same value = 20 and the following result is achieved.


Wednesday, July 22, 2015

Call Function From PostgreSQL with Qt SQL

Qt SQL enables programmers to call written functions from PostgreSQL database. Example project contains following table and functions from PostgreSQL server.

Configuration required to run this application:

1-) PostgreSQL 9.4.4
2-) Qt Version 5.4.0
3-) Qt Creator 3.2.2

PostgreSQL has got its own database programming language named with PL/pgSQL and following functions implemented in PL/pgSQL.

-- Table: person

-- DROP TABLE person;

CREATE TABLE person
(
  id integer NOT NULL,
  name text NOT NULL,
  age integer NOT NULL,
  address character(50),
  CONSTRAINT person_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE person
  OWNER TO test;


person table is filled with the following sample records/rows in order to see the execution result.

INSERT INTO person(
            id, name, age, address)
    VALUES (1, 'paul', 12, 'adana');

INSERT INTO person(
            id, name, age, address)
    VALUES (2, 'tufan', 15, 'ankara');

INSERT INTO person(
            id, name, age, address)
    VALUES (3, 'colin', 18, 'antep');

First PostgreSQL PL/pgSQL function returns the max age from the person table.
CREATE OR REPLACE FUNCTION maxAge()
RETURNS integer AS $$
declare
 max_age integer;
BEGIN
   SELECT max(age) into max_age FROM person;
   RETURN max_age;
END;
$$ LANGUAGE plpgsql;

maxAge() plpgsql function called with a select statement from pgAdmin III Query Tool.
SELECT maxage();

Output of the call of the maxage() function from PostgreSQL database is "18".

Second PostgreSQL PL/pgSQL function returns the age of the person whose name is sent as a parameter from the person table.
CREATE OR REPLACE FUNCTION getAgeOfPersonByName( nameOfPerson text )
RETURNS integer AS $$
declare
 person_age integer;
BEGIN
   SELECT age into person_age FROM person where name=nameOfPerson;
   RETURN person_age;
END;
$$ LANGUAGE plpgsql;

getAgeOfPersonByName( nameOfPerson text ) plpgsql function called with a select statement from pgAdmin III Query Tool.

SELECT getAgeOfPersonByName('paul');
Output of the call of the getAgeOfPersonByName('paul') function from PostgreSQL database is "12".

After creating the required tables and functions in PostgreSQL, now it is time to write our Qt application that calls these PL/pgSQL functions from PostgreSQL with Qt SQL.

Following sample project created by qt creator and contains following files :

1- QtSQLCallFunctionFromPostgreSQL.pro
2- main.cpp


QtSQLCallFunctionFromPostgreSQL.pro file contains project configuration :

TEMPLATE  = app
CONFIG   += console
CONFIG   -= app_bundle
QT       += core sql
QT       -= gui
TARGET = QtSQLCallFunctionFromPostgreSQL
SOURCES += main.cpp
Sample project only contains main.cpp file as source file. maxAge and getAgeOfPersonByName PL/pgSQL functions from PostgreSQL are called and return values are displayed in the terminal.

#include <QCoreApplication>
#include <QtSql>
#include <QDebug>

int main()
{
    const char* driverName = "QPSQL";
    QSqlDatabase db( QSqlDatabase::addDatabase(driverName) );
    db.setConnectOptions();
    db.setHostName("localhost");
    db.setDatabaseName("testdb");
    db.setUserName("test");
    db.setPassword("test");

    db.open();

    QString functionNameToCall = "maxAge";
    QSqlQuery* query = new QSqlQuery(db);
    query->prepare(QString("SELECT %1()").arg(functionNameToCall));
    query->exec();

    QString maxAgeOfPersonTable;
    while (query->next())
    {
        maxAgeOfPersonTable = query->value(0).toString();
    }

    qDebug() << maxAgeOfPersonTable;

    functionNameToCall = "getageofpersonbyname";
    QString name = "paul";
    query->prepare(QString("SELECT %1(?)").arg(functionNameToCall));
    query->addBindValue(name);
    query->exec();

    QString personAge;
    while (query->next())
    {
        personAge = query->value(0).toString();
    }

    qDebug() << personAge;

    delete query;
    db.close();

    return 0;
}


getageofpersonbyname PL/pgSQL function takes a parameter and the parameter is binded by addBindValue function of QSqlQuery. When the Qt application runs in the terminal the following output is displayed.


Sunday, July 19, 2015

Connect to PostgreSQL From Qt Application with Qt Sql

Qt comes with Qt Sql APIs in order to perform database related operations. Qt SQL's APIs consist of mainly three parts.
- Driver Layer
- SQL API Layer
- User Interface Layer

In order to connect to a database from Qt application, related database driver needs to be configured.
After setting connection to a specific database from Qt application, SQL API helps to achieve common database operations such as open-close connection, query tables, etc.

Configuration required to run this application:

1-) PostgreSQL 9.4.4
2-) Qt Version 5.4.0
3-) Qt Creator 3.2.2


Create sql script for Person table: You can use pgAdmin tools in order to create tables on postgreSQL database.

-- Table: person

-- DROP TABLE person;

CREATE TABLE person
(
  id integer NOT NULL,
  name text NOT NULL,
  age integer NOT NULL,
  address character(50),
  CONSTRAINT person_pkey PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE person
  OWNER TO test;


Following sample project created by qt creator and contains following files :

1- QSqlConnection.pro
2- QSQLDbHelper.h
3- QSQLDbHelper.cpp
4- main.cpp



QSqlConnection.pro file contains project configuration :

TEMPLATE  = app
CONFIG   += console
CONFIG   -= app_bundle
QT       += core sql
QT       -= gui
SOURCES  += main.cpp \
    QSQLDbHelper.cpp

HEADERS += \
    QSQLDbHelper.h


In this example qt sql project QSQLDbHelper.h class header file contains database related functions.


#ifndef QSQLDBHELPER_H
#define QSQLDBHELPER_H

#include <QtSql>
#include <QString>
#include <QDebug>

class QSQLDbHelper
{
public:
    QSQLDbHelper(const char* driver);
    ~QSQLDbHelper();
    QSqlDatabase* connect( const QString& server,
                           const QString& databaseName,
                           const QString& userName,
                           const QString& password );
    void disConnect();

    int selectRowCountResult(QSqlQuery* query);
    bool executeInsert(QSqlQuery* query);
    bool executeUpdate(QSqlQuery* query);
    bool executeDelete(QSqlQuery* query);

private:
    QSqlDatabase* db;
};

#endif // QSQLDBHELPER_H


QSQLDbHelper.cpp file contains implementation details for the following functions :

1- Class constructor/desctructor
2- Db connect
3- Db disconnect
4- selectRowCount
5- insert operation
6- update operation
7- delete operation


#include "QSQLDbHelper.h"

QSQLDbHelper::QSQLDbHelper(const char* driver)
{
    db = new QSqlDatabase( QSqlDatabase::addDatabase(driver) );
}

QSQLDbHelper::~QSQLDbHelper()
{
    qDebug() << "Called Destructor!";
    delete db;
}

QSqlDatabase* QSQLDbHelper::connect( const QString& server,
                                     const QString& databaseName,
                                     const QString& userName,
                                     const QString& password )
{
    db->setConnectOptions();
    db->setHostName(server);
    db->setDatabaseName(databaseName);
    db->setUserName(userName);
    db->setPassword(password);

    if(db->open()) {
        return db;
    }
    else {
        return NULL;
    }
}

int QSQLDbHelper::selectRowCountResult(QSqlQuery* query)
{
    bool queryRes = query->exec();
    if (query->lastError().type() != QSqlError::NoError || !queryRes)
    {
        qDebug() << query->lastError().text();
        return -1;
    }

    int recordCount = 0;
    while (query->next())
    {
        qDebug() << "Field 1 : " << query->value(0).toString() 
                 << "Field 2 : " << query->value(1).toString();
        ++recordCount;
    }

    return recordCount;
}

bool QSQLDbHelper::executeInsert(QSqlQuery* query)
{
    db->transaction();
    bool queryRes = query->exec();
    if (query->lastError().type() != QSqlError::NoError || !queryRes)
    {
        qDebug() << query->lastError().text();
        db->rollback();
        return false;
    }
    db->commit();
    return true;
}

bool QSQLDbHelper::executeUpdate(QSqlQuery* query)
{
    db->transaction();
    bool queryRes = query->exec();
    if (query->lastError().type() != QSqlError::NoError || !queryRes)
    {
        qDebug() << query->lastError().text();
        db->rollback();
        return false;
    }
    db->commit();
    return true;
}

bool QSQLDbHelper::executeDelete(QSqlQuery* query)
{
    db->transaction();
    bool queryRes = query->exec();
    if (query->lastError().type() != QSqlError::NoError || !queryRes)
    {
        qDebug() << query->lastError().text();
        db->rollback();
        return false;
    }
    db->commit();
    return true;
}

void QSQLDbHelper::disConnect()
{
    qDebug() << "Disconnected From Database!";
    db->close();
}


In order to make database related operations from a qt application it is required to include "QtSql" header file into the related source file.

QSqlDatabase class represents a database in your application. A transaction is started and concluded by using rollback() and commit() functions of QSqlDatabase.

QSqlQuery class executes passed sql queries on postgresql database.

Main method in the main.cpp file calls implemented connect, disconnect and CRUD operation methods from QSQLDbHelper class.


#include <iostream>

#include <QDebug>
#include "QSQLDbHelper.h"

int main()
{
    qDebug() << "Compiled with Qt Version = " << QT_VERSION_STR;

    const char* driverName = "QPSQL";
    QSQLDbHelper* qSQLDbHelper = new QSQLDbHelper(driverName);
    QSqlDatabase* db = qSQLDbHelper->connect("localhost", "testdb", "test", "test");

    if(db->open()) {

        QSqlQuery* query = new QSqlQuery(*db);
        query->setForwardOnly(true);

        // Select empty person table
        QString name = "Paul";
        if( !query->prepare(QString("SELECT id, name from person where name = ? ")) )
        {
            qDebug() <<"Error = " << db->lastError().text();
            return -1;
        }
        else
            query->addBindValue(name);

        int queryResultRowCount = qSQLDbHelper->selectRowCountResult(query);
        qDebug() << "Initial Row Count = " << queryResultRowCount << "\n";

        // insert into empty person table
        QString id = "1";
        QString age = "34";
        QString address = "istanbul";
        if( !query->prepare(
        QString("INSERT INTO person( id, name, age, address) VALUES ( ?, ?, ?, ?)") ))
        {
            qDebug() <<"Error = " << db->lastError().text();
            return -1;
        }
        else
        {
            query->addBindValue(id);
            query->addBindValue(name);
            query->addBindValue(age);
            query->addBindValue(address);
        }

        bool result = qSQLDbHelper->executeInsert(query);
        if( result )
            qDebug() << "Successful insert";
        else
            qDebug() << "Insert failed";

        // Select person table with 1 matching record
        if( !query->prepare(
        QString("SELECT id, name from person where name = ? ")))
        {
            qDebug() <<"Error = " << db->lastError().text();
            return -1;
        }
        else
            query->addBindValue(name);

        queryResultRowCount = qSQLDbHelper->selectRowCountResult(query);
        qDebug() << "After Insert Row Count = " << queryResultRowCount << "\n";


        // Update person table
        name = "Paul2";
        if( !query->prepare(QString("UPDATE person set name=? where id =? ")) )
        {
            qDebug() <<"Error = " << db->lastError().text();
            return -1;
        }
        else
        {
            query->addBindValue(name);
            query->addBindValue(id);
        }

        result = qSQLDbHelper->executeUpdate(query);
        if( result )
            qDebug() << "Successful update";
        else
            qDebug() << "Update failed";

        // Select person table with 0 no matching record
        if( !query->prepare(
        QString("SELECT id, name from person where name = ?")) )
        {
            qDebug() <<"Error = " << query->lastError().text();
            return -1;
        }
        else
        {
            query->addBindValue(name);
        }
        queryResultRowCount = qSQLDbHelper->selectRowCountResult(query);
        qDebug() << "After Update Row Count = " << queryResultRowCount << "\n";


        // Delete from person table whose name is Paul2
        // name = "Paul2";
        if( !query->prepare(QString("Delete from person where name =? ")) )
        {
            qDebug() << "Error = " << db->lastError().text();
            return -1;
        }
        else
        {
            query->addBindValue(name);
        }

        result = qSQLDbHelper->executeDelete(query);
        if( result )
            qDebug() << "Successful delete";
        else
            qDebug() << "Delete failed";

        // Select person table with 0 no matching record
        if( !query->prepare(
        QString("SELECT id, name from person where name = ? ")) )
        {
            qDebug() << "Error = " << db->lastError().text();
            return -1;
        }
        else
        {
            query->addBindValue(name);
        }
        queryResultRowCount = qSQLDbHelper->selectRowCountResult(query);
        qDebug() << "After Delete Row Count = " << queryResultRowCount << "\n";

        delete query;
    }
    else {
        qDebug() << "Something went Wrong:" << db->lastError().text();
    }

    qSQLDbHelper->disConnect();
    delete qSQLDbHelper;

    return 0;
}


In main function database connection is established and related database related operations are being tested. Parametric, dynamic sql queries created by using addBindValue method of QSqlQuery.

Output of the execution of this program shows database operation results from Qt application in terminal.