新手问题。如何在c ++中填充std::string
然后将填充结果分配给变量?
我看着setfill
和setw
,但我看到的所有例子都用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功能来实现这一点,还是我必须自己动手?
您可以使用与std :: cout相同的格式说明符来使用ostringstream。
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;
}
一般情况下,您可以使用std::stringstream
并利用流的所有“实用程序”,但“导出”为std::string
。
std::stringstream aSs;
aSs << std::left << std::setfill('0') << std::setw(12) << 123;
aSs.str(); // <-- get as std::string