如何将stringstream内容转换为char类型而不是字符串类型 [英] How to put stringstream contents into char type instead string type

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

问题描述

每个人都知道 stringstream.str()需要一个字符串变量类型来存储 stringstream.str()

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

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

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

是否可以这样做?

p>

推荐答案

为什么不是

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

不能在你的函数之外自由地给出 p :它的生命周期是绑定到 s 的生命周期,因此你可能想

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.

编辑2:如@David建议,上面的复制意味着复制内容,而不是指针本身。有几种方法。您可以手动执行(旧方式从C继承) - 这是通过等函数完成的 std :: strcpy 。这种方式相当复杂,因为它涉及手动资源管理,通常不鼓励,因为它导致一个更复杂和容易出错的代码。或者你可以使用智能指针或容器:它可以是 std :: vector< char> std :: unique_ptr / std :: shared_ptr

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.

我个人会选择第二种方式。看到这个和@ Oli的回答的讨论,它可以是有用的。

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

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

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