字符串转数字 数字转字符串

几种方法


http://hi.baidu.com/mycral/item/43bca5df670ce51fd68ed0da

数字转字符串:

用C++的streanstream:

#include <sstream>
#Include <string>
string num2str(double i)
{
        stringstream ss;
        ss<<i;
        return ss.str();
}


字符串转数字:

int str2num(string s)
 {   
        int num;
        stringstream ss(s);
        ss>>num;
        return num;
}


上面方法很简便, 缺点是处理大量数据转换速度较慢..
C library中的sprintf, sscanf 相对更快

可以用sprintf函数将数字输出到一个字符缓冲区中. 从而进行了转换...
例如:
已知从0点开始的秒数(seconds) ,计算出字符串"H:M:S",  其中H是小时, M=分钟,S=秒

         int H, M, S;
        string time_str;
        H=seconds/3600;
        M=(seconds%3600)/60;
        S=(seconds%3600)%60;
        char ctime[10];
        sprintf(ctime, "%d:%d:%d", H, M, S);             // 将整数转换成字符串
        time_str=ctime;                                                 // 结果 



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

    char    str[] = "15.455";
    int     i;
    float     fp;
    sscanf( str, "%d", &i );         // 将字符串转换成整数   i = 15
    sscanf( str, "%f", &fp );      // 将字符串转换成浮点数 fp = 15.455000
    //打印
    printf( "Integer: = %d ",  i+1 );
    printf( "Real: = %f ",  fp+1 ); 
    return 0;

输出如下:
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

swap

Exchanges the arrays of characters of two strings.

stod

 

stof

 

stoi

 

stold

 

stoll

 

stoul

 

stoull

 

to_string

 

to_wstring

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值