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*
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
