字符串转化成int
将str转化成int
#include<stdio.h>
#include<string>
int err = 0;
int str_to_int(char *s)
{
long sum = 0;
bool isPositive = true;
bool isZeroStart = true;
bool flag = false;
char c;
int maxInt = 0x7fffffff;
bool flag2;
bool isNumStart = false;
while (*s != '\0') {
c = *s;
flag = (c >= '0' && c <= '9');
if (c == '-') {
if (isNumStart) {
err = 9;
printf("- is illegal");
return -1;
}
isPositive = false;
s++;
} else if (c == '0' && isZeroStart) {
isNumStart = true;
s++;
} else if (c == '+') {
if (isNumStart) {
err = 9;
printf("+ is illegal");
return -1;
}
if (*(s + 1) == '\0') {
err = 10;
printf("num is +\n");
return -1;
}
flag2 = (*(s + 1) >= '0' && *(s + 1) <= '9');
if (!flag2) {
err = 11;
printf("num is ilegal\n");
return -1;
}
++s;
} else if (flag) {
sum = sum * 10 + c - '0';
isNumStart = true;
if (sum >= maxInt) {
break;
}
isZeroStart = false;
++s;
} else {
err = 11;
printf("num is ilegal\n");
return -1;
}
}
if (isPositive) {
return sum;
}
return -sum;
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("input num please\n");
return -1;
}
char *str = argv[1];
int num = str_to_int(str);
if (err) {
printf("parse str to num is err\n ");
return -1;
}
printf("num = %d\n", num);
return 0;
}
该程序支持+,-开头,允许000开头
作者: 盛夏落木
出处: https://www.cnblogs.com/wanshuafe/
关于作者:专注云存储,文件系统领域,请多多赐教!
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(wanshuafe@163.com)咨询.