Converting ostream into standard string

别说谁变了你拦得住时间么 提交于 2019-11-28 16:25:53

问题


I am very new to the C++ STL, so this may be trivial. I have a ostream variable with some text in it.

ostream* pout;
(*pout) << "Some Text";

Is there a way to extract the stream and store it in a string of type char*?


回答1:


     std::ostringstream stream;
     stream << "Some Text";
     std::string str =  stream.str();
     const char* chr = str.c_str();

And I explain what's going on in the answer to this question, which I wrote not an hour ago.




回答2:


The question was on ostream to string, not ostringstream to string.

For those interested in having the actual question answered (specific to ostream), try this:

void someFunc(std::ostream out)
{
    std::stringstream ss;
    ss << out.rdbuf();
    std::string myString = ss.str();
}



回答3:


Try std::ostringstream

   std::ostringstream os;
   os<<"Hello world";
   std::string s=os.str();
   const char *p = s.c_str();


来源:https://stackoverflow.com/questions/3513173/converting-ostream-into-standard-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!