Search code examples
c++stringpadding

How to pad strings of different lengths with '----' so that in the end all strings will have the same length?


Im writing a Log report for n tests im running on my code. The output goes into a log which looks something like this:

test subject number 12 had result 0.12334 ------> PASSED!!!
test subject number 1 had result 56 ------> PASSED!!!
test subject number 123 had result 2 ------> FAILED!!!

and so on.

I would like that the PASSED or FAILED statement would be aligned with each other regardless of the length of the string that came before them, it should look like this:

test subject number 12 had result 0.12334 ------> PASSED!!!
test subject number 1 had result 56 ------------> PASSED!!!
test subject number 123 had result 2 -----------> FAILED!!!

I have this function that pads the ---> arrows and PASSED or FAILED statement but it doesn't do the job right:

void AddPassedOrFailed(std::string& LogMessage, bool passed)
    {
        int initial_size = LogMEssage.size();
        for ( int i = initial_size ; i < 200 - initial_size ; i ++)
        {
            if (i == 200 - initial_size -1)
                LogMessage += (passed ? "> PASSED!!! ": "> FAILED!!!");
            else
                LogMessage += "-";
        }
        LogMessage +="\n";
    }

LogMessage is one line like this: "test subject number 12 had result 0.12334 "


Solution

  • It is always a good investment of time to spend browsing your favorite C++ reference manual. Where, for example, one can learn about very useful std::string overloads. Such as the two argument version of resize():

    void AddPassedOrFailed(std::string& LogMessage, bool passed)
    {
         LogMessage.resize(200, '-');
         LogMessage += (passed ? "> PASSED!!!\n": "> FAILED!!!\n");
    }