c++-字符串转化为整形(atoi)

来源:互联网 发布:system01.dbf数据大 编辑:程序博客网 时间:2024/05/16 09:43

c++-字符串转化为整形(atoi)

atoi为库函数,坐在的头文件为#include

 //原型:int atoi(char *str); //用法,atoi传入的参数为字符指针,而并非string类型 #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) {     int a;double d;     char str[] = "1024";     char strd[] = "3.1415";     a = atoi(str);d =atof(strd);     printf("%d/n",a);     printf("%g/n",d);     return 0; }

atio的实现
特别注意边界条件。写程序就像砌围墙,得先把边界条件弄好。

//判断字符是否是空格等特殊转义字符,这些输入没有显式输入isspace(int x){    if(x==' '||x=='/t'||x=='/n'||x=='/f'||x=='/b'||x=='/r')        return 1;    else         return 0;}//判断是否是数字,过滤掉其他字符如字母,@等符号isdigit(int x){    if(x<='9'&&x>='0')                 return 1;     else         return 0;}//atoi的实现int atoi(const char *nptr){      int c;              /* current char */      int total;         /* current total */      int sign;           /* if '-', then negative, otherwise positive */      /* skip whitespace */      while ( isspace((int)(unsigned char)*nptr) )          ++nptr;      //处理正负符号      c = (int)(unsigned char)*nptr;      sign = c;           /* save sign indication */      if (c == '-' || c == '+')                         c = (int)(unsigned char)*nptr++;    //遇到正负号则从下一位开始转换      total = 0;      /**开始转化**/      while (isdigit(c)) {          total = 10 * total + (c - '0');     /* accumulate digit */          c = (int)(unsigned char)*nptr++;    /* get next char */      }      //负数情况      if (sign == '-')          return -total;      else          return total;   /* return result, negated if necessary */}

C++中string to int的函数stringstream
头文件#include<sstream>
e.g:

string result=”10000”;int n=0;stream<<result;stream>>n;//n等于10000

重复利用stringstream对象

注意:如果你打算在多次转换中使用同一个stringstream对象,记住再每次转换前要使用clear()方法;
e.g.

#include <sstream>#include <iostream>int main(){    std::stringstream stream;    int first, second;    stream<< "456"; //插入字符串    stream >> first; //转换成int    std::cout << first << std::endl;    //在进行多次转换前,必须清除stream    stream.clear();//清除错误标志    stream.str("");//清除内容“456”    stream << true; //插入bool值    stream >> second; //提取出int    std::cout << second << std::endl;}

在多次转换中重复使用同一个stringstream(而不是每次都创建一个新的对象)对象最大的好处在于效率。stringstream对象的构造和析构函数通常是非常耗费CPU时间的

在类型转换中使用模板
你可以轻松地定义函数模板来将一个任意的类型转换到特定的目标类型。例如,需要将各种数字值,如int、long、double等等转换成字符串,要使用以一个string类型和一个任意值t为参数的to_string()函数。to_string()函数将t转换为字符串并写入result中。使用str()成员函数来获取流内部缓冲的一份拷贝:

template<class T>void to_string(string & result,const T& t){   ostringstream oss;//创建一个流   oss<<t;//把值传递如流中   result=oss.str();//获取转换后的字符转并将其写入result}//这样,你就可以轻松地将多种数值转换成字符串了:to_string(s1,10.5);//double到stringto_string(s2,123);//int到stringto_string(s3,true);//bool到string

可以更进一步定义一个通用的转换模板,用于任意类型之间的转换。函数模板convert()含有两个模板参数out_type和in_value,功能是将in_value值转换成out_type类型:

template<class out_type,class in_value>out_type convert(const in_value & t){    stringstream stream;    stream<<t;//向流中传值    out_type result;//这里存储转换结果    stream>>result;//向result中写入值    return result;}//这样使用convert():double d;string salary;string s=”12.56”;d=convert<double>(s);//d等于12.56salary=convert<string>(9000.0);//salary等于”9000”

自己写一个算法转化

long convert(char*string,long integer)  {      for(int sLen=strlen(string),i=0;i<sLen;)    integer+=(long)(string[i++]-'0')*pow(10.0,sLen-i-1);      return integer;  }  
原创粉丝点击