Home > Blockchain >  Collecting many printf calls in a single string
Collecting many printf calls in a single string

Time:11-28

I am dealing with some code that performs RC4 encryption algorithm with some params passed into the function. From there I am trying to append the generated hash to an empty string but have failed with a few of my attempts. I had seen the use of snprintf() but how could I go about converting the code below to save what gets printed to a string?

    for (size_t i = 0, len = strlen(plaintext); i < len; i  ) {
        printf("|xhhx| ", hash[i]);
    }

CodePudding user response:

Why not use 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();
}

CodePudding user response:

Just work with std::string::data after determining the size of the output of 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("|xhhx| ", 33) << '\n';

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

    std::cout << output;
}

Note: If you know a reasonable upper bound for the number of characters of the output, you could use a char array allocated on the stack for output instead of having to use 2 calls to std::snprintf...

  •  Tags:  
  • c
  • Related