Home > Net >  Generate C string with space behind such that space is automatically adjusted
Generate C string with space behind such that space is automatically adjusted

Time:02-02

I am trying to create a text generator which shall generate following output:

localparam  OR_CHANNEL_DATA_WIDTH               = 2;
localparam  RQ_CHANNEL_DATA_WIDTH               = 18;
localparam  RSP_CHANNEL_DATA_WIDTH              = 8;
localparam  VIN_CHANNEL_DATA_WIDTH              = 43;
localparam  VOUT_CHANNEL_DATA_WIDTH             = 123;

I used std::stringstream to build the stream:

std::stringstream ss;
ss << "localparam OR_CHANNEL_DATA_WIDTH" << std::right << std::setw(80) << " = " << Sth::get() << ";\n";
ss << "localparam RQ_CHANNEL_DATA_WIDTH" << std::right << std::setw(80) << " = " << Sth::get() << ";\n";
ss << "localparam RSP_CHANNEL_DATA_WIDTH" << std::right << std::setw(80) << " = " << Sth::get() << ";\n";

Sth::get() will return number. There are many such lines that needs to be generated. But the text in the middle is not fixed. How can I achieve the above output

CodePudding user response:

I am not sure you can do it in a simple streaming operation, but easily write a small function that does the job:

#include <iostream>
#include <sstream>
#include <iomanip>

const std::string adjust_width(const std::string& s, int width)
{
    std::stringstream temp;
    temp << std::left << std::setw(width) << s;
    return temp.str();
}


int main()
{
    std::stringstream ss;
    ss << adjust_width("localparam OR_CHANNEL_DATA_WIDTH", 80) << " = " << 1 << ";\n";
    ss << adjust_width("localparam RQ_CHANNEL_DATA_WIDTH", 80) << " = " << 12 << ";\n";
    ss << adjust_width("localparam RSP_CHANNEL_DATA_WIDTH", 80) << " = " << 123 << ";\n";
    ss << adjust_width("localparam VIN_CHANNEL_DATA_WIDTH", 80) << " = " << 1234 << ";\n";

    std::cout << ss.str();

    return 0;
}
  •  Tags:  
  • c 11
  • Related