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*
基础教程推荐
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
