C++ 将 int 和 string 转换为 char* [英] C++ convert int and string to char*

查看:23
本文介绍了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*的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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