字符串转为整数

一个由数字组成的字符串,怎么转为整数?
注意的问题:

1.字符串是否为NULL2.是正整数还是负整数;
    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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值