C++ can setw and setfill pad the end of a string?

折月煮酒 提交于 2019-11-30 11:26:39

You can use manipulators std::left, std::right, and std::internal to choose where the fill characters go.

For your specific case, something like this could do:

#include <iostream>
#include <iomanip>
#include <string>

const char* C_TEXT = "Constant text ";
const size_t MAXWIDTH = 10;

void print(const std::string& var_text, int num)
{
    std::cout << C_TEXT
              // align output to left, fill goes to right
              << std::left << std::setw(MAXWIDTH) << std::setfill('.')
              << var_text << ": " << num << '\n';
}

int main()
{
    print("1234567890", 42);
    print("12345", 101);
}

Output:

Constant text 1234567890: 42
Constant text 12345.....: 101

EDIT: As mentioned in the link, std::internal works only with integer, floating point and monetary output. For example with negative integers, it'll insert fill characters between negative sign and left-most digit.

This:

int32_t i = -1;
std::cout << std::internal
          << std::setfill('0')
          << std::setw(11)  // max 10 digits + negative sign
          << i << '\n';
i = -123;
std::cout << std::internal
          << std::setfill('0')
          << std::setw(11)
          << i;

will output

-0000000001
-0000000123

Something like:

cout << left << setw(MAXWIDTH) << setfill('.') << temp << ':' << Number << endl;

Produces something like:

derp..........................:234
herpderpborp..................:12345678
#include <iostream>
#include <iomanip>

int main()
{
   std::cout
      << std::setiosflags(std::ios::left) // left align this section
      << std::setw(30)                    // within a max of 30 characters
      << std::setfill('.')                // fill with .
      << "Hello World!"
      << "\n";
}

//Output:
Hello World!..................
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!