C++ 将 ostream 转换为标准字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3513173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:00:44  来源:igfitidea点击:

Converting ostream into standard string

c++stliostream

提问by Stephen Diehl

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

我对 C++ STL 很陌生,所以这可能是微不足道的。我有一个ostream带有一些文本的变量。

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

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

有没有办法提取流并将其存储在类型的字符串中char*

采纳答案by James Curran

     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.

我解释了我在一小时前写的这个问题的答案中发生了什么。

回答by Foo

The question was on ostreamto string, notostringstreamto string.

问题是关于ostream字符串,而不是ostringstream字符串。

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

对于那些有兴趣回答实际问题(特定于ostream)的人,请尝试以下操作:

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

回答by Prasoon Saurav

Try std::ostringstream

尝试 std::ostringstream

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