关于字符串转化为整型数的安全代码

来源:百度知道 编辑:UC知道 时间:2024/06/28 00:18:55
代码的目的是将字符串转化为整型数,对任何输入(能通过编译)都要有适当的处理,最后返回正确的结果,代码如下。
int Test_atoi(char* s)
{
int a = 0;
int len;
int flg;
char *str, *p, *q;

if (s == NULL) // 检查s是否具有内存地址空间
{
cout<< "Cannot be NULL" <<endl;
}
else
{
a = atoi(s); // 将字符串转化为整数

// 下面的代码检查字符串转换为整型数是否正确
for(; *s == ' ' || *s == '0' ; s++) // 去除字符串开头的空格
{
q = s;
}
if (*s == '\0')
{
p = q;
}
else
{
p = s;
}

len = strlen(p); // 返回字符串长度
str = new char[len + 1]; // 分配内存空间
if (str) // 分配成功
{
itoa(a, str, 10); // 将整型数转化为字符串
str[len] = '\0'; //字符号街为符号

flg = strcmp(str, p); //检查两个字符串是否匹配
if (flg != 0)
{
cout<< "Input error!" <<endl;
}
else
{
cout<< a

这段代码应该没有问题,我在visual.net下测试过了。做了一点小改动,但不影响算法。你用的是什么开发环境?我在你用的环境中再试试。
#include <iostream>

using namespace std;

int Test_atoi(char* s)
{
int a = 0;
int len;
int flg;
char *str, *p, *q;

if (s ==0) //////////////////////////////// 检查s是否具有内存地址空间
{
cout<< "Cannot be NULL" <<endl;
}
else
{
a = atoi(s); // 将字符串转化为整数

// 下面的代码检查字符串转换为整型数是否正确
for(; *s == ' ' || *s == '0' ; s++) // 去除字符串开头的空格
{
q = s;
}
if (*s == '\0')
{
p = q;
}
else
{
p = s;
}

len = strlen(p); // 返回字符串长度
str = new char[len + 1]; // 分配内存空间
if (str) // 分配成功
{
itoa(a, str, 10); // 将整型数转化为字符串
str[len] = '\0'; //字符号街为符号

flg = strcmp(str, p); //检查两个字符串是否匹配
if