一个由数字组成的字符串,怎么转为整数?
注意的问题:
1.字符串是否为NULL;
2.是正整数还是负整数;
3.输入的字符串是否全为数字呢;
4.字符串很长,是否OVERFLOW;
代码直接贴上:
// StrToint.cpp : 定义控制台应用程序的入口点。
//visual studio 2013
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace std;
int StrToInt(char *str);
int _tmain(int argc, _TCHAR* argv[])
{
char ss[] = "-2147445";
StrToInt(ss);
system("pause");
return 0;
}
int StrToInt(char *str)
{
static const int MAX_INT = (int)((unsigned)~0 >> 1);
static const int MIN_INT = -(int)((unsigned)~0 >> 1) - 1;
//cout << MAX_INT << endl;
unsigned int n = 0;
//The NUM is null?
if (!str)
{
return 0;
}
//delete space of the string
while (isspace(*str))
{
++str;
}
//The number is negative number or positive number?
int sign = 1;
if (*str == '+' || *str == '-')
{
if (*str == '-')
{
sign = -1;
}
++str;
}
//Whether it is a digit?
while (isdigit(*str))
{
//Overflow?
int c = *str - '0';
if (sign > 0 && (n > MAX_INT / 10 || (n == MAX_INT / 10 && c > MAX_INT % 10)))
{
n = MAX_INT;
break;
}
else if (sign < 0 && (n>(unsigned)MIN_INT / 10 || (n ==
(unsigned)MIN_INT / 10 && c > (unsigned)MIN_INT % 10)))
{
n = MIN_INT;
break;
}
n = n * 10 + c;
++str;
}
if (sign>0)
{
cout << n << endl;
}
else {
cout << '-' << n << endl;
}
return 1;
}