C++ convert int and string to char*(C++ 将 int 和 string 转换为 char*)
问题描述
这有点难,我想不通.
我有一个 int 和一个字符串,我需要将它存储为 char*,int 必须是十六进制
I have an int and a string that I need to store it as a char*, the int must be in hex
即
int a = 31;
string str = "a number";
我需要用制表符将两者分开放入 char* 中.
I need to put both separate by a tab into a char*.
输出应该是这样的:
1F a number
推荐答案
适当的包括:
#include <sstream>
#include <ostream>
#include <iomanip>
类似这样的:
std::ostringstream oss;
oss << std::hex << a << ' ' << str << '
';
从以下位置复制结果:
oss.str().c_str()
注意 c_str
的结果是一个临时的(!) const char*
所以如果你的函数使用 char *
你需要在某处分配一个可变副本.(也许将其复制到 std::vector
.)
Note that the result of c_str
is a temporary(!) const char*
so if your function takes char *
you will need to allocate a mutable copy somewhere. (Perhaps copy it to a std::vector<char>
.)
这篇关于C++ 将 int 和 string 转换为 char*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 将 int 和 string 转换为 char*


- Stroustrup 的 Simple_window.h 2022-01-01
- 静态初始化顺序失败 2022-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- C++ 协变模板 2021-01-01
- 近似搜索的工作原理 2021-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01