Saturday 25 May 2013

nstrcat.cpp (strcat with a variable sized argument list)


//No fail safe included in this version -- to be added later

#include <cstdarg>
#include <iostream>
using namespace std;

char* nstrcat(char* str, ...);
int main() {
  char* result;
char sample[50] = "Hello";
result = nstrcat(sample, " this", " is", " a", " test");
return 0;
}
char* nstrcat(char* str, ...) {
va_list args;
va_start(args, str);
char* temp;
int i = 0;
int n = 0;
while(str[i])
i++;    //moving to the end of the initial string
while(temp = va_arg(args, char*)) { //moving to the next argument each loop
for(n=0;temp[n];i++, n++) {
str[i] = temp[n];
}
}
va_end(args);
return str;
}

Tuesday 21 May 2013

Changing a char to an int with a simple function

//challenge program for OOP344 written by Matt MacEachern
//21/05/13

#include <iostream>
using namespace std;

int AscToInt(const char* ch);

int main() {              
        int number;
        number = AscToInt("-14234");
        return 0;
}

int AscToInt(const char* ch) {
        int posneg;
        int num;
        posneg = 1;
        num = 0;
        (*ch == '-') && (posneg = -1) && ch++;       //changing to negative if there is a '-'
        (*ch == '+') && (ch++);

        while(*ch) {
                num *= 10;      //adding a 0 at the end of the int so a new value can be added
                num += *ch - 48;  //bringing the value that ch points to down to its value in ascii
                ch++;
        }
        num *= posneg;
        return num;
}