字符串和数字相互转换

来源:互联网 发布:apache weblogic 插件 编辑:程序博客网 时间:2024/05/16 19:05
       在boost中,有一个万能转换工具,它就是boost::lexical_cast,它可以在任何数值间进行转换,当然也包括字符串和数字间的转换。
#include <iostream>#include <boost/lexical_cast.hpp>#include <string>using namespace std;using namespace boost;int main(){    string s="123";int a=lexical_cast<int>(s);cout<<a<<endl;double b=lexical_cast<double>(s);cout<<b<<endl;int d=5678;string str=lexical_cast<string>(d);cout<<str<<endl;cout<<str.substr(1,str.size()-1)<<endl;try {int c=lexical_cast<int>("wrong number");}catch(bad_lexical_cast &e){        cout<<e.what()<<endl;}}

       这是很方便的,平时我们应该尽可能用这种转换。但是有的时候,在刷题的时候,有的时候怕它的环境中并没有链接boost库,这就需要自己手动去实现。

       可以使用stringstream流。

       

#include <iostream>#include <string>#include <sstream>using namespace std;int main(){string s="123";    stringstream ss(s);int num;ss>>num;cout<<num<<endl;int n=456;stringstream str;str<<n;cout<<str.str()<<endl;}

       但是stringstream有几个细节要注意。当多次转换重复使用同一个stringstream对象时,会发生错误。       

  一般说来,人们对于清空流缓存区,想到的都是clear()函数,但是stringstream中clear()函数并不清空流的缓存区,只是重置了流的标志而已,如那种标志错误的标志类似的。在stringstream中调用.str(“”)清空流标志。 
但是我自己在程序中测试(后面可以看到),我调用。str(“”)清流反而不行,我调用clear()还行。 
在网上找到的解释: 
那么把stringstream类内部的缓冲区正确的清空方式是什么呢? 
stringstream ss; 
答案是: ss.str(“”) 方法. 
另外,如果需要把格式化后的字符串通过>>输出到字符串, 必须每次都调用clear()方法! 
所以保险起见,以后清空流两个方法都用。

      除了流这么麻烦,c提供函数sprintf。

     格式是int sprintf(char *buffer,const char *format,[argument])

     如: char buf[10];

      sprintf(buf,"%d",123);

     要考虑的是buf要有足够的长度容纳要写入的数字。

      与之相反的是:可以用atoi将一个字符串转换成数字。

     

      

0 0
原创粉丝点击