c++ 在单个字符串中收集多个printf调用

odopli94  于 2022-12-01  发布在  其他
关注(0)|答案(2)|浏览(110)

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

for (size_t i = 0, len = strlen(plaintext); i < len; i++) {
        printf("|x%02hhx| ", hash[i]);
    }
wn9m85ua

wn9m85ua1#

为什么不使用C++。

#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();
}
gojuced7

gojuced72#

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

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数组进行输出,而不必使用2次std::snprintf调用...

相关问题