rdu-cpp

杨柳不折
随笔 - 13, 文章 - 0, 评论 - 4, 引用 - 0
数据加载中……

string.format in c++

C#里面的string.Format用着很爽,可是在C++里面拼字符串好像就不那么便捷了。
对一般内置类型来说,sprintf当能满足大部分需求。而对于自定义类型而言,可以利用stringstream来曲线救国:

#include <sstream>
string foo()
{
    stringstream ss;
    ss 
<< "x:" << _x << "\ty:" << _y;
    
return ss.str();
}

当然了,这里_x,_y的类型均需实现了
friend ostream&  operator << (ostream&  s, ObjClass& m)

----------------华丽的分割线--------------

Input/output string stream class

stringstream

stringstream provides an interface to manipulate strings as if they were input/output streams.

ref of stringstream from cplusplus.com

posted on 2009-01-22 16:14 rdu 阅读(11065) 评论(1)  编辑 收藏 引用 所属分类: Tips

评论

# re: int to string or other things to string  回复  更多评论   

thread@
http://www.cnblogs.com/lshguang89/archive/2008/06/09/1216334.html

c++ int to string(整型到字符串)
1. int sprintf( char *buffer, const char *format [, argument] ... );
<stdio.h>
例如:
int ss;
char temp[64];
string str;
ss = 1000;
sprintf(temp, "%d", ss);
string s(temp);
//调用string的方法
cout<<s.c_str()<<endl;//1000
cout<<s.size()<<endl; //长度为4

2.char *_itoa( int value, char *string, int radix );
<stdlib.h>
例如:
char buffer[20];
int i = 3445;
_itoa( i, buffer, 10 );
string s(buffer);


3. stringstream( )
<sstream.h>
例如:
int hello=4;
stringstream ss;
ss<<hello;
string s=ss.str();
//调用string的方法
cout<<s.c_str()<<endl;
2009-01-22 16:17 | rdu

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理