下午刚写的一个strtol函数,跑了几种特殊情况,倒是都可以过了。
等过段时间,会把c函数库的其它几个常用函数也有个自己的实现出来。
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
// s:source string for conversion, base:decimal,hex or octal,etc,no binary
long StrToLong(char *s, int base = 10)
{
// judge for null pointers
if (!s)
return LONG_MIN;
// skip ws or tab
while (*s == ' ' || *s == '\t')
++s;
// for sign + or -
long sign = 1;
if (*s == '-') {
sign = -1;
++s;
}
else if (*s == '+')
++s;
// leave it 10 as default, then check 10 more
if (*s == '0') {
if (s[1] == 'x' || s[1] == 'X') {
base = 16;
s += 2;
}
else
base = 8;
}
long num = 0;
static int i = 0; // debug option
while(*s) {
i++; // debug option
if (*s < '0' || *s > '9')
return num;
num = num * base + *s - '0';
++s;
// checking for overflow
if (num > LONG_MAX/10) {
return sign > 0 ? LONG_MAX : LONG_MIN;
}
}
return num * sign;
}
int main(int argc, char *argv[])
{
if (argc < 2) {
cout << "format ./strtoint string" << endl;
exit(EXIT_FAILURE);
}
cout << "the result is:" << StrToLong(argv[1]) << endl;
return 0;
}