首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在一个字符串中收集多个printf调用

在一个字符串中收集多个printf调用
EN

Stack Overflow用户
提问于 2022-11-28 08:27:30
回答 2查看 59关注 0票数 0

我正在处理一些代码,这些代码使用传递到函数中的一些参数来执行RC4加密算法。从那里开始,我试图将生成的散列附加到一个空字符串中,但几次尝试都失败了。我已经看过snprintf()的使用了,但是我如何转换下面的代码来保存打印到字符串中的代码呢?

代码语言:javascript
复制
    for (size_t i = 0, len = strlen(plaintext); i < len; i++) {
        printf("|x%02hhx| ", hash[i]);
    }
EN

回答 2

Stack Overflow用户

发布于 2022-11-28 08:43:05

为什么不使用C++。

代码语言:javascript
复制
#include <iomanip>
#include <iostream>
#include <sstream>
#include <cstring>

int main() {
    char plaintext[] = "12345";
    char hash[] = "123\xf0\x0f";
    std::stringstream out;
    for (size_t i = 0, len = strlen(plaintext); i < len; i++) {
        out << "|x"
            << std::setfill('0') << std::setw(2) << std::setbase(16)
            // ok, maybe this is the reason.
            << 0xff & hash[i]
            << "| ";
    }
    std::cout << out.str();
}
票数 7
EN

Stack Overflow用户

发布于 2022-11-28 08:46:02

确定了std::string::data输出的大小后,只需使用std::snprintf

代码语言:javascript
复制
template<class...Args>
std::string PrintFToString(char const* format, Args...args)
{
    std::string result;
    char c;
    int requiredSize = std::snprintf(&c, 1, format, args...);
    if (requiredSize < 0)
    {
        throw std::runtime_error("error with snprintf");
    }

    result.resize(requiredSize);

    int writtenSize = std::snprintf(result.data(), requiredSize+1, format, args...);
    assert(writtenSize == requiredSize);

    return result;
}

template<class...Args>
void AppendPrintFToString(std::string& target, char const* format, Args...args)
{
    char c;
    int requiredSize = std::snprintf(&c, 1, format, args...);
    if (requiredSize < 0)
    {
        throw std::runtime_error("error with snprintf");
    }

    auto const oldSize = target.size();
    target.resize(oldSize + requiredSize);

    int writtenSize = std::snprintf(target.data() + oldSize, requiredSize+1, format, args...);
    assert(writtenSize == requiredSize);
}

int main() {
    std::cout << PrintFToString("|x%02hhx| ", 33) << '\n';

    std::string output;
    for (int i = 0; i != 64; ++i)
    {
        AppendPrintFToString(output, "|x%02hhx| ", i);
        output.push_back('\n');
    }

    std::cout << output;
}

注意:如果您知道输出字符数的合理上限,则可以使用堆栈上分配的char数组进行输出,而不必使用对std::snprintf的2次调用.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74597850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档