str相关的函数实现

下午刚写的一个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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值