在c ++中填充并分配std :: string

问题描述 投票:1回答:3

新手问题。如何在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功能来实现这一点,还是我必须自己动手?

c++ padding
3个回答
4
投票

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

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

然后

auto padded{ ss.str() };

2
投票

可以使用可用的字符串操作,如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


0
投票

一般情况下,您可以使用std::stringstream并利用流的所有“实用程序”,但“导出”为std::string

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

Live Demo

© www.soinside.com 2019 - 2024. All rights reserved.