您的位置:首页 > 其它

数字的字符串转换成 对应整数输出

2014-04-19 00:02 239 查看
#include<iostream>
int Str_To_Int(const char*p);
using namespace std;
int main()
{     
char*ptr="-987321";
int l=Str_To_Int(ptr);
cout<<l<<endl;

return 0;

}

//数字的字符串转换成 对应整数输出,例如:“78965”转换成输出:78965
int Str_To_Int(const char*p)
  {   
int temp=0,num=0;
if(p==NULL)
 {cout<<"the string is NULL !"<<endl;return 0;}
else
{
if(*p=='\0')
   {cout<<"the string is \"\\0\"(空串) ";
    cout<<endl;
return 0;}
else
{   //检查正负;
if(*p=='+')
       	p++;
   else if(*p=='-')
      {
    p++;
        temp=1;
       }
//开始转换;
       	while(*p!='\0')
           	{  
          if((*p>='0')&&(*p<='9'))
            {num=num*10+(*p-'0');
                  ++p;}
             else
            {    num=0;
              cout<<"have invalid character!";
      cout<<endl;
          break;
        }
           	}
      if(temp) //如果是负数;
     num=0-num; //添加负号;
             }
 
     }
 return num;

 }

<
9f0e
/div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐