【发布时间】:2020-08-24 06:24:28
【问题描述】:
我的目标:我正在使用 Visual Studio 2015 中的 MFC 构建一个应用程序。我创建了一个包含两列的表,其中包含许多寄存器的数字和值,如下所示:
为了方便地填写此表,我想创建一个 for 循环,它将 LPCSTR 字符串(自动解释为 const char)发送到名为 InsertItem 的 CListCtrl 类的成员函数。我希望这个 LPCSTR 字符串看起来像一个十六进制数 0x01 或 0x14,而前缀 0x 之后的值将由十六进制基数的循环索引确定。例如:
char buffer[3*sizeof(int)];
int l_iItem;
for (int index = REGS_NUMBER; index >= 0; index--) {
// Somehow make buffer look like 0xN when N is the index value in hex representation stuffed with
// zeroes if needed;
l_iItem = m_EditableList.InsertItem(LVIF_TEXT | LVIF_STATE, 0, buffer, 0, LVIS_SELECTED, 0, 0);
m_EditableList.SetItemText(l_iItem, 1, "00000000");
我看到了很多关于这个主题的问题,但几乎所有人都提出了解决这个问题的方法(正如在 cmets 上所说的那样)。如果有人可以向我推荐适当的功能,我将不胜感激。
谢谢。
================================================ ==============================
按照 Tushar 的建议,我尝试添加这些标题:
#include <iostream>
#include <sstream>
#include <iomanip>
并尝试运行以下代码:
char* n;
int i = 7;
//std::istringstream s("2A");
n << std::hex << std::showbase << i;
std::cout << n;
我得到的错误:
expression must have integral or unscoped enum.
'hex' is not a member of std.
'showbase' is not a member of std.
undeclared identifier.
undeclared identifier.
另一个试验:正如 cmets 所建议的那样,我尝试使用 ostringstream 而不是 char*,如下所示:
std::ostringstream ss;
int i = 7;
ss << std::hex << std::showbase << i;
std::string str = ss.str();
const char *output = str.c_str();
我得到了同样的错误,尽管我包含了所有必要的标题。可能是什么问题?
【问题讨论】:
-
创建一个
char数组并使用fprintf将数字写入其中。 -
打印是你想要做的,但你想“打印”到一个字符串而不是控制台。阅读
std::ostringstream。 -
<< std::hex不适用于char*。它是标准库的 IOStreams 部分的一部分。它将适用于std::cout、std::ofstream、std::ostringstream等。
标签: c++ formatting hex