Archive for February, 2012

List for single integer – QUEUE

Posted: February 17, 2012 in Uncategorized

File: queue.h

#ifndef __FS_QUEUE_H__
#define __FS_QUEUE_H__

class Queue;

class Node{
  int _data;
  Node* _next;
  Node(int data, Node* next = (Node*)0);
  friend class Queue;
};

class Queue{
  Node* _head;
public:
  Queue();
  virtual ~Queue();
  int remove();
  void add(int val);
  bool isEmpty();
};

#endif

File: queue.cpp

#include "queue.h"

Node::Node(int data, Node* next){
  _data = data;
  _next = next;
}
Queue::Queue(){
  //Initialize and head point it to NULL 
  _head = (Node*)0;
}
Queue::~Queue(){
  //Method 1
  /*while(Node* p = _head){
    _head = _head->_next;
    delete p;
  }*/

  //Method 2
  while(_head) remove();
}
int Queue::remove(){
  //Initializing a veriable to hold the current
  //data in order to return at the end
  int ret = _head->_data;

  //Copying the current pointer so we can use that
  //to delete after. This is must be done to avoid 
  //memory leak
  Node* toDel = _head;

  //Now head will point to second or next element
  _head = _head->_next;

  //Delete permanently the one removed from list.
  //So it will remove from memory completely
  delete toDel;

  //Return the deleted data
  return ret;
}
void Queue::add(int val){
  //Here we create a Node and that will pointed 
  //by _head. Also using the private copy 
  //constructor to add the given parameter "val"
  //as new data and copy the current _head as 
  //next.
  _head = new Node(val, _head);
}
bool Queue::isEmpty(){
  //Here we are checking where that is pointing
  //to. If it is empty, the head will point to 
  //NULL. So if this is pointing NULL, it will 
  //return true.
  return !_head;
}

File: queuemain.cpp

#include <iostream>
using namespace std;

#include "queue.h"
int main(){
  bool done = false;
  int input;
  int i=-1;
  Queue Q;
  while(!done) {
    cout<<"Enter an integer (0 to terminate and remove):";
    cin>>input;
    if(input) Q.add(input);
    else done=true;
    i++;
  }
  cout<<i<<((i==1)?(" integer Added"):(" integers Added"))<<endl<<endl<<endl;
  cout<<"QUEUE LIST: "<<endl<<endl;
  while(!Q.isEmpty()) cout<<Q.remove()<<" -> ";

  cout<<"NULL"<<endl<<endl;
  return 0;
}

How to work with SVN…

Posted: February 14, 2012 in OOP344

Here is my YouTube video link to show you how to work with SVN repo for OOP344 project.

Please comment!

Answer to challenging question

Posted: February 9, 2012 in OOP344

Here is my one line statement, which will work for this program…

int validMonth(int mon, char* errmes){
  return (strcpy(errmes, "Invalid month (1<=month<=12)") && mon > 0 && mon <=12);
}

NOTE:
Since someone has posted already the more efficient answer,

int validMonth(int mon, char* errmes){
  return (mon > 0 && mon <=12) || !strcpy(errmes, "Invalid month (1<=month<=12)");
}

I am just to show you here, this can be done with && operator. Also, my return statement will modify/replaceĀ  the errmes even if it is true. For good programming practice, we have to avoid extra process. So please don’t use this type of method.

Thanks!

MiniPrint – bugs fixed version

Posted: February 9, 2012 in OOP344
#include <cstdio>
#include <cstdarg>
using namespace std;

void miniprint(const char *format, ...){
  va_list ap;
  va_start(ap, format);
  while(*format){
    if(*format == '%'){
      format++;
      switch(*format){
        case 'd':
          printf("%d", va_arg(ap,int));
          break;
        case 'f':
          printf("%0.2f", va_arg(ap,double));
          break;
        case 's':
          printf("%s", va_arg(ap,char*));
          break;
        case 'x':
          printf("%x", va_arg(ap,int));
          break;
        case 'X':
          printf("%X", va_arg(ap,int));
          break;
        case 'p':
          printf("%p", va_arg(ap,void*));
          break;
        default:
          putchar(*format);
      }
      format++;
    }
    else{
      putchar(*format++);
    }
  }
  va_end(ap);
}

int main(){
  miniprint("hello I am %s and I make %f Dollars a year\n", "Homer", 12345.67);
  return 0;
}

Concatenate by command line argument

Posted: February 9, 2012 in OOP344

Basic Code without error message and safe guard.

#include <cstdio>

int concat(char* file1, char* file2) {
  FILE* fp1 = fopen(file1, "a");
  FILE* fp2 = fopen(file2, "r");
  char ch;
  int status = 0;
  if (fp2 && fp1) {
    for(;(ch=fgetc(fp2)) != EOF; fputc(ch, fp1));
    fclose(fp2);
    fclose(fp1);
    status = 1;
  }
  return status;
}

int main(int argc, char** argv) {
  int i=1;
  if (argc > 2){
    for (i = 1; i < argc-1 && concat(argv[1], argv[i+1]); i++);
    if (i == argc-1)
      printf("Concatenation is Success!!\n");
  }
  return 0;
}

Detailed Code with error messages and safe guard.

#include <cstdio>

bool concat(char* file1, char* file2) {
  FILE* fp1 = fopen(file1, "r");
  FILE* fp2 = fopen(file2, "r");
  char ch;
  bool status = 0;
  bool err = 0;

  if(!fp1) {
    fp1 = fopen(file1, "a");
    if(!fp1) {
      printf("ERROR: Can't open %s!!\n", file1);
    }
    else {
      err = 1;
      printf("%s is created!\n", file1);
    }
  }
  else{
    fclose(fp1);
    fp1 = fopen(file1, "a");
    if(!fp1) {
      printf("ERROR: Can't open %s!!\n", file1);
    }
    else err = 1;
  }

  if(!fp2 && err) {
    printf("ERROR: Can't open %s!!\n", file2);
  }

  if (fp2 && fp1) {
    for(;(ch=fgetc(fp2)) != EOF; fputc(ch, fp1));
    fclose(fp2);
    fclose(fp1);
    status = 1;
  }
  return status;
}

int main(int argc, char** argv) {
  int i=1;
  if (argc == 1)
    printf("No destination file  selected to perform this action!\n");
  else if (argc == 2)
    printf("No files were selected to merge with %s.\n",argv[1]);
  else if (argc > 2){
    for (i = 1; i < argc-1 && concat(argv[1], argv[i+1]); i++){
      printf("%s << %s... success\n",argv[1],argv[i+1]);
    }
    if (i == argc-1)
      printf("Concatenation is Success!!\n");
  }
  return 0;
}

Class for STRING ARRAY

Posted: February 8, 2012 in OOP344

STRING.H

/***************************************************/
/* File     : string.h                             */
/* Writen by: Thevakaran Virutthasalam             */
/***************************************************/

#ifndef _TV_STRING_H_
#define _TV_STRING_H_

class Str{
  char* _string;
  unsigned int _size;
  void AloCopy(const Str&);
  char* Strcat(char*, const char*);
  char* Strcpy(char*, const char*);
  int   Strlen(const char*);
  int   Strcmp(const char*,const char*);

public:
  Str (unsigned int);
  Str (const Str&);
  Str& operator=(const Str&);
  Str& operator=(const char*);
  Str& operator=(const char);
  Str& operator+=(const Str&);
  Str& operator+=(const char*);
  Str& operator+=(const char);
  friend  Str operator+(const Str&, const Str&);
  friend  Str operator+(const Str&, const char*);
  friend  Str operator+(const Str&, const char);
  virtual ~Str();
  char&   Str::operator[](unsigned int);
  unsigned int size()const;
};

#endif

STRING.CPP

/***************************************************/
/* File     : string.cpp                           */
/* Writen by: Thevakaran Virutthasalam             */
/***************************************************/
#include "string.h"

void Str::AloCopy(const Str& X){
  _string = new char[X.size()+1];
  for(unsigned int i=0;i<X.size();_string[i] = X._string[i++]);
  _size = X.size();
}

Str::Str(unsigned int size){
  //Initialize the object with given size
  _string = new char[size+1];
  *_string = '\0';
  _size = size;
}

Str::Str(const Str& X){
  //Initialize the object with given of another object
  AloCopy(X);
}

Str& Str::operator=(const Str& str){
  //Assigning operator for string object
  if(this != &str){
    delete[] _string;
    AloCopy(str);
  }
  return *this;
}

Str& Str::operator=(const char* s ){ 
  //Assigning operator for null terminated string
  unsigned int size = Strlen(s);
  if(_size<size || _size>(size*3)){
    char* new_string = new char[size*2+1];
    delete[] _string;
    _string = new_string;
    _size = size*2;
  }
  Strcpy(_string, s);
  return *this;
}

Str& Str::operator=(const char c){
  //Assigning operator for a single char
  if(_size < 2 || _size > 100) { 
  //Checking to add/remove enough memory.
	  delete [] _string;
	  char* new_char = new char[11];
	  _size = 10;
	  _string = new_char;
  }
  *_string= c;
  *(_string+1)='\0';
  return *this;
}

Str& Str::operator+=(const Str& X){
  //Appending operator for string object
  unsigned int i;
  unsigned int j;
  char* new_string = new char[X.size()+_size+1];
  for(i=0;_string[i]!='\0' && i<_size;new_string[i]=_string[i++]);
  for(j=0;X._string[j]!='\0' && j<=X.size();new_string[j+i]=X._string[j++]);
  new_string[j+i]='\0';
  delete[] _string;
  _size += X.size();
  _string = new_string;
  return *this;
}

Str& Str::operator+=(const char* s){
  //Appending operator for null terminated string
  unsigned int i;
  unsigned int j;
  unsigned int len=Strlen(s);
  char* new_string = new char[len+_size+1];
  for(i=0;_string[i]!='\0' && i<_size;new_string[i] = _string[i++]);
  for(j=0;s[j]!='\0';new_string[j+i] = s[j++]);
  new_string[j+i]='\0';
  delete[] _string;
  _size += len;
  _string = new_string;
  return *this;
}

Str& Str::operator+=(const char c){
  //Appending operator for a sigle char
  unsigned int i = Strlen(_string);
  if (i+1<_size) {
    char* new_string = new char[_size+2];
    for(i=0;_string[i]!='\0' && i<_size;new_string[i] = _string[i++]);
    new_string[i++]=c;
    new_string[i]='\0';
    delete[] _string;
    _size += 1;
    _string = new_string;
  }
  else {
    _string[i]=c;
    _string[i+1]='\0';
  }
  return *this;
}

Str operator+(const Str& lhs, const Str& rhs){
  Str copyArr = lhs;
  copyArr += rhs; //using append operator of object
  return copyArr;
}

Str operator+(const Str& lhs, const char* s){
  Str copyArr = lhs;
  copyArr += s; //using append operator of string
  return copyArr;
}

Str operator+(const Str& lhs, char c){
  Str copyArr = lhs;
  copyArr += c; //using append operator of char
  return copyArr;
}

char& Str::operator[](unsigned int index){
  //Index operator to ruturn char at given index position
  //of the string
  if(index >= _size){
    char* new_string = new char[index*2 + 1];
    for(unsigned int i=0;i<_size;new_string[i] = _string[i++]);
    delete[] _string;
    _size = index*2;
    _string = new_string;
  }
  return _string[index];
}

unsigned int Str::size()const{
  //return the size of current object.
  return _size;
}

int Str::Strlen(const char* str){
  //String length function
  int i;
  for(i=0; str[i] != '\0'; i++);
  return i;
}

char* Str::Strcpy(char* dest, const char* source){
  //String copy function
  int i;
  for(i=0;source[i]!='\0';i++){
    dest[i] = source[i];
  }
  dest[i]='\0';
  return dest;
}

char* Str::Strcat(char* dest, const char* srce){
	unsigned int i = Strlen(dest);
	Strcpy(dest+i, srce);
	return dest;
}

int Str::Strcmp(const char* str1, const char* str2){
  //String compare function
  int result=0;
  for(int i=0; !result && str1[i] != '\0' 
    && str2[i] != '\0'; i++){
    if(str1[i] > str2[i]){
      result = 1;
    }
    else if(str1[i] < str2[i]){
      result = -1;
    }
  }
  return result;
}

Str::~Str(){
  //Distructor of Str object
  delete[] _string;
}