Thursday, May 26, 2011

The classic "atoi" question

//Language C++
#include <iostream>
using namespace std;

int atoi(char *s)
{
  int i=0;
  while(*s)
  {
    if (*s ==' ' || *s =='\t')
       s++;
    else {
    if ( *s < '0' || *s > '9' )
         return i;  
    i = i*10 + (*s- '0');
    s++;
    }
  }
  return i;
}

int my_atoi(char* pStr) {

    if (pStr == NULL) {
        printf("ERROR: null string.\n");
        return -1;
    }

    int num = 0;

    int pos;
    for (pos = 0; ; pos++) {
        char currChar = *(pStr+pos);

        // Check whether the current char is not a digit
        if ( currChar < '0' || currChar > '9' )
            return num;

        // Read the number and add it to the 'num' variable
        num = (num*10) + (int) currChar - (int)'0';
    }
    return num;
}

int s_atoi(char *s)
{
  int i = 0;
  while(*s)
  {
    if ( *s < '0' || *s > '9' )
         return i;
    i = (i<<3) + (i<<1) + (*s - '0');
    cout <<i <<endl;
    s++;
  }
  return i;
}

/////////////
int Atoi(const char *pstr)
{
int sign = 1;
int num = 0;
while (*pstr == ' ' || *pstr == '\t')
{
pstr++;
}
if (*pstr == '-')
{
sign = -1;
pstr++;
}
while (*pstr)
{
if (*pstr >= '0' && *pstr <= '9')
{
num = 10 * num + *pstr - '0';
}
else
{
return num * sign;
}
pstr++;
}
return (num * sign);
}
//////////////

int main(){
char *s = "  9885 pigs";
cout << atoi(s) <<endl;
getchar();
cout << my_atoi(s) <<endl;
getchar();
cout << s_atoi(s) <<endl;
getchar();
cout << Atoi(s) <<endl;
getchar();
cout<<"-----ascii----"<<endl;
for(char ch = 'A'; ch <= 'Z'; ch++)
//insert cout statement here, as clearly your professor wont like
    printf("%x %i %c \n" , ch,ch,ch);
    getchar();
return 0;
}

No comments:

Post a Comment