几种方法
http://hi.baidu.com/mycral/item/43bca5df670ce51fd68ed0da
数字转字符串:
用C++的streanstream:








字符串转数字:







上面方法很简便, 缺点是处理大量数据转换速度较慢..
C library中的sprintf, sscanf 相对更快
可以用sprintf函数将数字输出到一个字符缓冲区中. 从而进行了转换...
例如:
已知从0点开始的秒数(seconds) ,计算出字符串"H:M:S", 其中H是小时, M=分钟,S=秒








与sprintf对应的是sscanf函数, 可以将字符串转换成数字









输出如下:
Integer: = 16
Real: = 16.455000
另外
mfc里面还有CString format函数,把数字转成字符串。
C语言里还有什么 atoi itoa _atow ....
<sstream> 的 stringstream类
http://zhidao.baidu.com/question/4386870.html
我用c++从文件中读到一个字符串 "12.32 12 35 25.3 36.366" 内容全是数字形式,怎么把它们转化为一个实数数组
你可以叫 stringstream 和 vector 帮忙。 下面的代码里 dbl_array 既是你要创建的实数数组(real 代表你读到的字符串)。 #include<vector> #include<string> #include<sstream> using namespace std; int main( ) { string real = "12.32 12 35 25.3 36.366"; stringstream ss( real ); vector< double > vd; // Collect all real numbers. double temp; while( ss >> temp ) vd.push_back( temp ); // Create the array. double *dbl_array = new double[ vd.size( ) ]; for( int i = 0; i < vd.size( ); ++i ) dbl_array[ i ] = vd[ i ]; }
std中的方法
在<string>下有些函数就是来做这个事的
在string的函数列表里也有 atoi 等
Specialized Template Functions
Exchanges the arrays of characters of two strings. | |