现在的位置: 首页 > 综合 > 正文

实现atoi() 测试页面如下

2018年04月09日 ⁄ 综合 ⁄ 共 645字 ⁄ 字号 评论关闭

原文作者链接:http://blog.csdn.net/sailtoy/article/details/16852149

测试源码:

#include <iostream>
#include <string>
using namespace std;

int isDigit(int s);
int my_atoi(const char* str);

int isDigit(int s)//判断是否是数字
{
	if(s >= '0' && s <= '9')
		return 1;
	else
		return 0;
}
int my_atoi(const char* str)
{
	int c;
	int sum = 0;
	int sign;
	if((*str)==' ' || (*str) == '\n' || (*str) == '\r' || (*str) == '\t')//判断是否是空格换行之类的空字符,有则跳过
		str++;

	sign = *str; //符号
	if(sign == '-' || sign == '+')//若有符号则跳过
		str++;
	c = (int)*str++;
	while(isDigit(c))
	{
		sum = 10 * sum + (c - '0');
		c = (int)*str++;
	}
	if(sign == '-')
		return -sum;
	else
		return sum;
}
void main()
{
	char str[512];
	while (1)
	{
		cout<<"请输入字符串:"<<endl;
		cin>>str;
		cout<<"字符串转换后:"<<endl;
		cout<<my_atoi(str)<<endl;;
	}
	
	system("pause");
}

抱歉!评论已关闭.