我正在处理一些代码,这些代码使用传递到函数中的一些参数来执行RC4加密算法。从那里开始,我试图将生成的散列附加到一个空字符串中,但几次尝试都失败了。我已经看过snprintf()的使用了,但是我如何转换下面的代码来保存打印到字符串中的代码呢?
for (size_t i = 0, len = strlen(plaintext); i < len; i++) {
printf("|x%02hhx| ", hash[i]);
}发布于 2022-11-28 08:43:05
为什么不使用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();
}发布于 2022-11-28 08:46:02
确定了std::string::data输出的大小后,只需使用std::snprintf
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次调用.
https://stackoverflow.com/questions/74597850
复制相似问题