如何将stringstream内容放入char而不是string类型? [英] How to put stringstream contents into char instead string type?

查看:74
本文介绍了如何将stringstream内容放入char而不是string类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个知道 stringstream.str()的人都需要一个字符串变量类型来将 stringstream.str()的内容存储到其中.

我想将 stringstream.str()的内容存储到char变量或char数组或指针中.

有可能这样做吗?

请用您的答案写一个简单的例子.

解决方案

为什么不只是

  std :: string s = stringstream.str();const char * p = s.c_str(); 

?

请注意,您不能在函数外随意赋予 p :它的生存期与 s 的生​​存期绑定,因此您可能想要复制它./p>

如@David所建议的那样,上面的 copy 表示内容的复制,而不是指针本身.有几种方法可以做到这一点.您可以手动执行此操作(从C继承"旧版方式)-使用 std :: strcpy .这种方法相当复杂,因为它涉及手动资源管理,通常不建议这样做,因为它会导致更复杂且易于出错的代码.或者,您可以使用智能指针或容器:它可以是 std :: vector< char> std :: shared_ptr .

我个人会选择第二种方式.参见对此的讨论和@Oli的答案,它可能会有用.

Every one know stringstream.str() need a string variable type to store the content of stringstream.str() into it .

I want to store the content of stringstream.str() into char variable or char array or pointer.

Is it possible to do that?

Please, write a simple example with your answer.

解决方案

Why not just

std::string s = stringstream.str();
const char* p = s.c_str();

?

Edit: Note that you cannot freely give the p outside your function: its lifetime is bound to the lifetime of s, so you may want to copy it.

Edit 2: as @David suggests, copy above means copying of the content, not the pointer itself. There are several ways for that. You can either do it manually (legacy way "inherited" from C) -- this is done with the functions like std::strcpy. This way is quite complicated, since it involves manual resources management, which is usually discouraged, since it leads to a more complicated and error-prone code. Or you can use the smart pointers or containers: it can be either std::vector<char> or std::unique_ptr/std::shared_ptr.

I personally would go for the second way. See the discussion to this and @Oli's answer, it can be useful.

这篇关于如何将stringstream内容放入char而不是string类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆