原文作者链接: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"); }