各位大虾,快帮帮忙,急急急!!!!!!!!!!(有关ostrstream)

peter_prince 2001-07-20 10:08:18
各位大虾,小弟在项目中有很多自定义的类都override了operator << and operator >>
但是由于写日志的要求(项目要求)和用法只能用char * 作为参数print,所以小弟就想
用class ostrsteam了,我是这么用的.
{
ostrstream os;
os << aa ;//aa 是我自己定义的类,override 了 operator << and operator >>
logs.write(LOG_DEV|ERROR,"%s",os.str());
//logs 是我们用于写日志的类的对象
//其实与下面那句的道理是一样的
//printf("%s",os.str());
}
(1)运行过程中发现,有时print出来的东东会比源信息多很多
(2)用purify(memory leak tool)检查总是报错说"Uninitialized Memory Write"
有谁用过this class , help me hurry!

...全文
169 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
peter_prince 2001-07-20
  • 打赏
  • 举报
回复
真的可以了,多谢.不过你说的ostringstream 我查了一下没有这个类(我用的是CC compiler)
xiterator 2001-07-20
  • 打赏
  • 举报
回复
二法解决:
void foo()
{
ostringstream o;
o << a;

//若还需使用 ostringstream

//方法一:
o.str(""); //两个"之间无空格,用于清空o缓冲。
....//重复使用o

//方法二:
ostringstream o2; //重新声明一新的ostringstream 对象。
}

至于ostrstream的解决办法采用freeze()可参见相关文档
xiterator 2001-07-20
  • 打赏
  • 举报
回复
几点建议:
1. 使用较新的ostringstream代替ostrstream。( (o.str()).c_str() )
2. 无论ostringstream or ostrstream都不会为operator << 调用自动添加'\0',所以要记得在所输出的信息最后加上 << ends。
3. 无论ostringstream or ostrstream都存在一旦调用了str()方法后,其中的信息自动上锁问题,有二法解决:
void foo()
{

}
xiterator 2001-07-20
  • 打赏
  • 举报
回复
下面信息仅供参考:<strstream>: strstream 较老,建议使用<sstream>: stringstream or ostringstream 代替ostrstream。
无论是strstream or stringstream 在调用operator << 时不会自动为你attach '\0',所以需要自已在最后增加ends,如下段代码:

#include <iostream>
#include <strstream> //better: <stringstream>
#include <iomanip>
using namespace std;

int main(int argc, char* argv[])
{
//printf("Hello World!\n");

char a[]="hello";

ostrstream out;
out << a << ends;
cout << out.str() << "he" << endl;

return 0;
}


xiterator 2001-07-20
  • 打赏
  • 举报
回复
ostringstream 即是typedef basic_ostringstream<char, char_traits<char>,
allocator<char> > ostringstream;
只要有basic_ostringstream<T>,char_traits<T>, allocator<T>定义即可,可以自已定义。

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧