Links

   Quran Explorer - Interactive Audio Recitations & Translations

Tuesday, July 10, 2007

Parsing Integers in C++

/This is my own function to parse integers from strings (char array to be exact)
//This was necessitated by the absence of 'parseInt()' in C and C++
//Created on July 2007 by Mabura

//important note: Angle brackets hav been left out bcoz this site treats them as //////html tags, so do add them before compiling.

#include iostream.h
#include string.h

//function to parse a string to an integer given a pointer to an array
int parseInt(char *ptrNumber)
{
char strNumber[10];
//store the string into a local variable
for(int i=0;i 'less than' 9;i++)
{
strNumber[i]=*ptrNumber;
ptrNumber++;
}

//'number' is used to construct the new integer using 'digit'
int number=0,digit=0;
int j=0;

//read from the last element of the array coming down
//this is done to get rid of the non essential values that fill the array
for(i=9;i 'greater than or equal to' 0;i--)
{
//check if number is between 0 and 9
if(int(strNumber[i]) 'greater or equal to' 48 && int(strNumber[i]) 'less or equal to' 57)
{
//get integer equivalent of the 'char'
digit=int(strNumber[i]);
//get the actual integer value (our zero is 48 and 9 is 57)
digit-=48;

//j is used to give 'digit' its appropriate 'weight' in the
//number (i.e ones,tens,hundreds etc)
j++;
for(int k=1;k 'less than' j;k++)
{
digit*=10;
}
}

number+=digit;
}

//test output before return;
cout number endl;
return number;

}

//This is the driver function to test the functionality of the parseInt()
//It actually creates arbitrary arrays with arbitrary values and then
//passes them to parseInt then gets the parsed integer. To prove that the
//number returned is an integer, this function tries to do integer manipulations
//then output the result to stdout.
void main()
{
char number[10];
char *ptrNumber=number;
//cout "Number ? " endl;
//cin number;
strcpy(number,"850");

int newInteger=parseInt(ptrNumber);

cout newInteger endl;
cout newInteger " + 50 = " (newInteger+50) endl;

}

No comments:

Post a Comment

Feel free to leave a comment