Thursday, September 17, 2009

OOP344 GetInt Challenge

Well, here she is, written from scratch and shiny as a penny, and no I don't know what I mean by that. I tried to eliminate any limitations or inefficiencies as I could, I don't think its perfect, but I tested it and it seems to run beautifully. I managed to accomplish this on my bus ride home from york to Hamilton, and subsequently haven't had anyone look it over yet, but I don't think I made any "no-no's" as Fardad calls it.

*EDIT* I noticed some mistakes in the code, I used C++ comments in C, for whatever reason I used val -= val * 2 instead of val = -val.

-------------------------------------------------------------------------------------------------


/*This GetInt fuction was written by JP Hughes (CloudScorpion)*/
/*This function first checks to see if val is negative, inserting a - in the first slot of the
strint array if it is. The function then proceeds to find the remainder of a divition of the
int val by 10, storing the value in the next slot in the array. Once complete, the function checks
if there is a - in the fist slot, if so if increases count to account for the difference, then
proceeds to reverse the values in the array so they do not appear backwards, then corrects the
count to its original value. Finally the function caps the array with a NULL byte at the end
of the string. */
void GetInt(char *strint, int val)
{
int count=0, c2 = 0; /*two counters required to keep track of the placement in for statements*/
char tmp; /*A char to hold a temporary value during the reversing process*/

if(val < 0) /*checks if the val is negative*/
{
strint[0] = '-'; /*if so, it inserts the - in the array*/
val = -val; /*inverts the value of val so it is positive*/
count ++;
c2++; /*counters are ajusted for later use*/
}
if(val > 0) /*This is used to ensure the value is not 0*/
{
for(; val > 0; count++)
{
strint[count] = val % 10 + 48; /*systematically inserts the numbers in reverse order*/
val /= 10; /* using ascii numbers, then removes the number from val*/
}
if(strint[0]=='-') count++; /*checks if the number is negative and adjusts the counter*/
for(; c2 < count/2 ; c2++)
{
tmp = strint[c2]; /*reverses the order of the numbers in the array by swapping the*/
strint[c2] = strint[count - c2 - 1]; /*numbers with the number on the other side of*/
strint[count -c2 - 1] = tmp; /* the array*/
}
if(strint[0]=='-') count--; /*corrects the counter if it was adjusted*/
}
else
{
strint[0] = '0'; /*if the value is 0, it is simply put in the first slot of the array*/
count++;
}
strint[count] = 0; /*finishes off the string with a NULL byte*/
return;
}

No comments:

Post a Comment