str相关的函数实现

来源:互联网 发布:python 5分钟执行一次 编辑:程序博客网 时间:2024/05/17 05:01
下午刚写的一个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 binarylong StrToLong(char *s, int base = 10){// judge for null pointersif (!s)return LONG_MIN;// skip ws or tabwhile (*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 moreif (*s == '0') {if (s[1] == 'x' || s[1] == 'X') {base = 16;s += 2;}elsebase = 8;}long num = 0;static int i = 0;// debug optionwhile(*s) { i++;// debug optionif (*s < '0' || *s > '9')return num;num = num * base + *s - '0';++s;// checking for overflowif (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;}


原创粉丝点击