将字符串转成整数以及整数转成字符串

1.将字符串转换成整数

           没什么难点,就是考虑的情况比较多。

#include<iostream>
#include<cctype>
#include<exception>
#include<climits>
#include<cstdio>
using namespace std;

long Str2Num(const char *str)
{
     if(!str)throw new std::exception("NULL String");
     bool isNegetive = false;
     int radix = 10;
     unsigned long ret = 0;
     if(*str == '-'){
	     isNegetive = true;
	     ++str;
     }else if(*str == '+')++str;
     if(*str == '0'&&(str+1)&&*(str+1)!='x'&&*(str+1)!='0'){
	     radix = 8;
	     ++str;
     }
     else if(*str == '0'&& tolower(*(str+1))=='x'){
	     radix = 16;
	     ++str;++str;
     }
     for(;*str!='\0';++str){
	     int ch = *str;
	     if((ch - '0') <radix){
	          ret = ret*radix + ch - '0';
         }
         else if(radix == 16 && ('a'<=tolower(ch)&&tolower(ch)<='f')){
	          ret = ret*radix + tolower(ch) - 'a' + 10;
         }
         else
	          throw new exception("Invalid num");
         if(ret>LONG_MAX)throw new exception("overfolw");
     }
     return isNegetive?(-ret):ret;
}
2.将整数转换成字符串(借用别人的,感觉还是有些情况没考虑到)
char * Num2Str(int Number)

{

   char ch,*str,*right,*left;

   unsigned int Value;

   str = (char *)malloc(12*sizeof(char));

   left = right = str;

   //如果是负数,则应加上负号,left、right向后走。

   if(Number < 0)

   {

      Value = -Number;

      *str = '-';

      left++,right++;

   }

   else

      Value = (unsigned)Number;

   //把数字转换成字符串(倒置的)

   while(Value)

   {

      *right = (Value%10)+0x30;

      Value = Value/10;

      right++;

   }

   *right-- = '\0';

   //把倒置的字符串正放过来

   while(right > left)

   {

      ch = *left;

       *left++ = *right;

       *right-- = ch;

   }

   return str;

}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C语言标准库函数`atoi()`将字符串转成整数。 `atoi()`函数的定义如下: ```c int atoi(const char *str); ``` 它的参数`str`是一个指向以NULL结尾的字符串的指针。`atoi()`函数会将这个字符串转成一个整数,并返回这个整数。如果字符串无法转成整数,则返回0。 例如,下面的代码将字符串`"12345"`转成整数: ```c int num = atoi("12345"); printf("%d\n", num); // 输出:12345 ``` 需要注意的是,如果字符串中包含不能转成数字的字符,`atoi()`函数会停止转换,并返回已经转换的整数。例如,下面的代码将字符串`"123abc"`转成整数: ```c int num = atoi("123abc"); printf("%d\n", num); // 输出:123 ``` 如果字符串以空格或制表符开头,则`atoi()`函数会忽略这些空格或制表符,并从第一个非空格或非制表符的字符开始转换。例如,下面的代码将字符串`" 12345"`转成整数: ```c int num = atoi(" 12345"); printf("%d\n", num); // 输出:12345 ``` 如果字符串以正号或负号开头,则`atoi()`函数会将正号或负号后面的数字转换整数,并返回这个整数。例如,下面的代码将字符串`"-12345"`转成整数: ```c int num = atoi("-12345"); printf("%d\n", num); // 输出:-12345 ``` 需要注意的是,`atoi()`函数只能将字符串转成int类型的整数。如果需要转换其他类型的整数(如long、long long等),则需要使用其他函数。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值