把字符串转化成整数

这道题看似很简单,实现其基本功能,大部分人都能用10行代码之内的代码解决。

...
while(*str)
{   
    count=count*10+str-'0';
    str++;
}
...

但是,当我们要把很多特殊的情况即测试用例都考虑进去,却不是一件容易的事。
比如:空指针、空字符串“”、正负号、溢出等方方面面的测试用例都考虑到,并在写代码时对这些特殊的输入都定义好合理的输出,

#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
enum State{
    Invalid,
    Valid,
};
int status = Invalid;//定义一个全局变量区分是合法输入("0")、不合法输入(空字符串)返回的0
int StrToInt(const char *str)
{
    if (str == NULL)//str非法
        return 0;
    if (*str == '0')
    {
        status = Valid;
        return 0;//字符串为数组0,即“0”,此时合法
    }
    if (*str == '\0')
        return 0;//空字符串"",非法
    else
    {
        long long sum = 0;
        int flag = 1;//正负号取值标志
        while (isspace(*str))
            str++;
        if (*str == '-')
        {
            flag = -flag;
            str++;
        }
        if (*str == '+')
            str++;
        while (*str)
        {
            if (isdigit(*str))
            {
                sum = sum * 10 + (*str - '0')*flag;
                if (sum > INT_MAX || sum < INT_MIN)
                {
                    printf("溢出\n");
                    return 0;
                }
            }
            else
                return (int)sum;
            str++;
        }
        status = Valid;
        return (int)sum;
    }
}
int main()
{
    char *p = "";
    int num = StrToInt(p);
    printf("%d\n", num);
    printf("status=%d\n", status);
    system("pause");
    return 0;
}

总结:

  1. 功能测试(输入的字符串表示正数、负数和0)
  2. 边界值测试(最大的正整数、最小是负整数)
  3. 特殊输入测试(输入字符串为NULL指针、输入字符串为空字符串、输入的字符串中有非数字字符等)

猜你喜欢

转载自blog.csdn.net/sifanchao/article/details/80472296