字符串转数字。
【分析】
主要是通过逐个字符获取并赋值给一个整型变量,每赋值一次*10即可。要做得完善点可以加上检测输入是否正确,正负数判断。
【代码】
#include "stdafx.h"
#include #include #include int Catoi(std::string str) { int result=0; //转换结果 bool isUp= true; //判断是否是正数 int start=0; //比较开始点 int end=str.size(); //比较结束点 if(str[0]=='-') { isUp = false; start =1; } else if(str[0]=='+') { start =1; } for(;start char temp = str[start]; if( temp <='9' && temp>='0' ) //非法字符除外 { result= result*10 +(str[start]-'0'); //主要算法,每赋值一次首先先乘以10再加数字 //char to int是ascII码, 因此要减‘0’ } } if(!isUp) { result*=-1; //如果是负数,乘以-1; } printf("%d\\n",result); return result; } int _tmain(int argc, _TCHAR* argv[]) { Catoi("-1"); Catoi("99"); Catoi("+65535"); Catoi("-99"); Catoi("-65535"); getchar(); return 0; }下载本文