在 C++ 中填充和分配 std::string

Padding and assigning a std::string in c++

新手问题。如何在 C++ 中填充 std::string,然后将填充后的结果分配给变量?

我正在查看 setfillsetw,但我看到的所有示例都以 std::cout 输出结果。例如:

std::cout << std::left << std::setfill('0') << std::setw(12) << 123;

我想要的是:

auto padded {std::left << std::setfill('0') << std::setw(12) << 123};

是否有标准函数可以完成此操作,还是我必须自己动手?

一般来说,您可以使用 std::stringstream 并利用所有 "utilities" 流,但 "export" 作为 std::string

std::stringstream aSs;
aSs << std::left << std::setfill('0') << std::setw(12) << 123;
aSs.str();  // <--  get as std::string

Live Demo.

您可以使用 ostringstream 和与 std::cout 相同的格式说明符。

 std::ostringstream ss;
 ss << std::left << std::setfill('0') << std::setw(12) << 123;

然后

auto padded{ ss.str() };

可以使用可用的字符串操作,例如 insert:

#include <iostream>
#include <string>

int main()
{
    std::string s = "123";
    s.insert(0, 12 - s.length(), '0');

    std::cout << s << std::endl;
    return 0;
}

https://ideone.com/ZhG00V