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;
}


No comments:

Post a Comment