字符串转成数字

来源:互联网 发布:零基础编程入门 编辑:程序博客网 时间:2024/06/06 20:54
#include "stdafx.h"#include <stdio.h>#include <stdlib.h>////////////////////////////////////////////////////////////////////////////1. 考虑 空字符//2. 考虑 正负号//3. 考虑 乱码字符//4. 考虑 溢出  long long 最大值的取值范围//5. C++有个函数atoi函数是转字符///////////////////////////////////////////////////////////////////////////long long StrToIntCore(const char *digit, bool minus);enum Status {    kValid = 0, //有效值    KInvalid    //无效值};int  g_nStatus = kValid;  //默认为有效值int StrToInt(const char *str){    g_nStatus = KInvalid;    long long num = 0;    if (str != NULL && *str != '\0')    {        bool minus = false;        //判断正负号        if (*str == '+')            str++;        else if (*str == '-')        {            str++;            minus = true;        }        if (*str != '\0')        {            num = StrToIntCore(str, minus);        }    }    return (int)num;}long long StrToIntCore(const char *digit, bool minus){    long long num = 0;    while (*digit != '\0')    {        if (*digit >= '0' && *digit <= '9')        {            int flag = minus ? -1 : 1;//正负判断            num = num * 10 + flag * (*digit - '0');//数字累加num            if ((!minus && num > 0x7FFFFFFF) || (minus && num < (signed int)0x80000000))            {                num = 0;                break;            }            digit++;        }        else        {            num = 0;            break;        }       }    if(*digit == '\0')    {        g_nStatus = kValid;    }    return num;}void Test(char *string){    int result = StrToInt(string);    if (result == 0 && g_nStatus == KInvalid)    {        printf("the input %s is invalid \n.", string);    }    else        printf("number for %s is %d \n", string, result);}int _tmain(int argc, _TCHAR* argv[]){    Test(NULL);    Test("");    Test("123");    Test("-123");    Test("+123");    Test("la123");    Test("+0");    Test("-0");    Test("+");    Test("-");    Test("+2147483647");    Test("-2147483647");    Test("+2147483648");    Test("-2147483648");    Test("+2147483649");    Test("-2147483649");    system("pause");    return 0;}
0 0
原创粉丝点击