码迷,mamicode.com
首页 > 其他好文 > 详细

字符串与数字互相转换

时间:2016-06-21 22:26:04      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:

新C++中已经有函数实现此类功能。

  • 数字转为字符串
 #include <sstream>  //include this to use string streams
 #include <string> 

int main()
{    
    int number = 1234;

    std::ostringstream ostr; //output string stream
    ostr << number; //use the string stream just like cout,
    //except the stream prints not to stdout but to a string.

    std::string theNumberString = ostr.str(); //the str() function of the stream 
    //returns the string.

    //now  theNumberString is "1234"  
}
  • 字符串转为数字
#include <sstream>
#include <string>
int main()
{
   std::string inputString = "1234 12.3 44";
   std::istringstream istr(inputString);
   int i1, i2;
   float f;
   istr >> i1 >> f >> i2;
   //i1 is 1234, f is 12.3, i2 is 44  
}

参见:

from

字符串与数字互相转换

标签:

原文地址:http://www.cnblogs.com/Searchor/p/5605045.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!