sprintf、ostringstream用法

分类: C/C加加 |
1、sprintf 函数
函数原型:
int sprintf( char *buffer, const char *format, [
argument] … );
函数功能:
把格式化的数据写入某个字符串缓冲区。
参数列表:
buffer:char型指针,指向将要写入的字符串的缓冲区。
format:char型指针,指向的内存里面存放的将要格式字符串。
[argument]...:可选参数,可以是任何类型的数据。
返回值:字符串长度(strlen)
eg:
1)//把整数123 打印成一个字符串保存在s
中。
sprintf(s, "%d", 123);
//产生"123"
2)可以指定宽度,不足的左边补空格:
sprintf(s, "��", 123, 4567);
//产生:" 123 4567"
3)当然也可以左对齐:
sprintf(s, "%-8d�", 123, 4567);
//产生:"123 4567"
4)也可以按照16 进制打印:
sprintf(s, "%8x", 4567); //小写16
进制,宽度占8 个位置,右对齐
sprintf(s, "%-8X", 4568); //大写16
进制,宽度占8 个位置,左对齐
这样,一个整数的16 进制字符串就很容易得到,但我们在打印16
进制内容时,通常想要一种左边补0 的等宽格式,那该怎么做呢?很简单,在表示宽度的数字前面加个0 就可以了。
sprintf(s, "X", 4567);
//产生:"000011D7"
上面以”%d”进行的10 进制打印同样也可以使用这种左边补0
的方式。
这里要注意一个符号扩展的问题:比如,假如我们想打印短整数(short)-1 的内存16
进制表示形式,在Win32 平台上,一个short 型占2 个字节,所以我们自然希望用4 个16 进制数字来打印它:
short si = -1;
sprintf(s, "X",
si);
产生“FFFFFFFF”,怎么回事?因为spritnf
是个变参函数,除了前面两个参数之外,后面的参数都不是类型安全的,函数更没有办法仅仅通过一个“%X”就能得知当初函数调用前参数压栈时被压进来的到底是个4 字节的整数还是个2 字节的短整数,所以采取了统一4
字节的处理方式,导致参数压栈时做了符号扩展,扩展成了32 位的整数-1,打印时4 个位置不够了,就把32 位整数-1 的8 位16
进制都打印出来了。
2、ostringstream
派生关系图:
http://www.cplusplus.com/img/arrow.gif | http://www.cplusplus.com/img/arrow.gif | http://www.cplusplus.com/img/arrow.gif |
ostringstream
|
ostringstream的构造函数形式:
- explicit
ostringstream ( openmode which = ios_base::out ); - explicit
ostringstream const( string & str, openmode which = ios_base::out );
explicit ostringstream ( openmode which = ios_base::out ); explicit ostringstream ( const string & str, openmode which = ios_base::out );
有时候,我们需要格式化一个字符串,但通常并不知道需要多大的缓冲区。为了保险常常申请大量的缓冲区以防止缓冲区过小造成字符串无法全部存储。这时我们可以考虑使用ostringstream类,该类能够根据内容自动分配内存,并且其对内存的管理也是相当的到位。
- #include
- #include
- #include
- using
namespace std; -
- void
main() - {
-
ostringstream ostr1; 构造方式1 -
ostringstream ostr2( // 构造方式2 -
-
-
ostr1 << << //2012 << endl; 格式化,此处endl也将格式化进ostr1中 -
cout << ostr1.str(); -
-
-
curPos //返回当前插入的索引位置(即put= ostr2.tellp(); pointer的值),从0开始 -
cout << = " << curPos << endl; -
-
ostr2.seekp(2); 手动设置put pointer的值 -
ostr2.put( 在put pointer的位置上写入'g',并将put pointer指向下一个字符位置 -
cout << ostr2.str() << endl; -
-
-
-
ostr2.clear(); -
ostr2.str( -
-
cout << ostr2.str() << endl; -
ostr2.str( -
cout << ostr2.str() << endl; -
ostr2 << 覆盖原有的数据,并自动增加缓冲区 -
cout << ostr2.str() << endl; - }
后一篇:函数指针、指针函数