我想在字符串中添加一个前导零的变量.我没有在谷歌上找到任何东西,没有人提及printf,但我想在没有(s)printf的情况下这样做.
有没有读者知道一种方式?
Rus*_*nov 59
如果你想要一个n_zero零的字段,我可以给这个单行解决方案:
std::string new_string = std::string(n_zero - old_string.length(), '0') + old_string;
Run Code Online (Sandbox Code Playgroud)
例如:old_string ="45"; n_zero = 4; new_string ="0045";
Rob*_*obᵩ 48
你可以使用std::string::insert,std::stringstream与流操纵或Boost.Format库:
#include <string>
#include <iostream>
#include <iomanip>
#include <boost/format.hpp>
#include <sstream>
int main() {
std::string s("12");
s.insert(0, 3, '0');
std::cout << s << "\n";
std::ostringstream ss;
ss << std::setw(5) << std::setfill('0') << 12 << "\n";
std::string s2(ss.str());
std::cout << s2;
boost::format fmt("%05d\n");
fmt % 12;
std::string s3 = fmt.str();
std::cout << s3;
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*fin 16
你可以这样做:
std::cout << std::setw(5) << std::setfill('0') << 1;
Run Code Online (Sandbox Code Playgroud)
这应该打印00001.
但请注意,填充字符是"粘性的",因此当您使用零填充时,您将不得不再次使用std::cout << std::setfill(' ');以获得通常的行为.
Mic*_*urr 14
// assuming that `original_string` is of type `std:string`:
std::string dest = std::string( number_of_zeros, '0').append( original_string);
Run Code Online (Sandbox Code Playgroud)
小智 8
这对我很有效。您不需要将 setfill 切换回 ' ',因为这是一个临时流。
std::string to_zero_lead(const int value, const unsigned precision)
{
std::ostringstream oss;
oss << std::setw(precision) << std::setfill('0') << value;
return oss.str();
}
Run Code Online (Sandbox Code Playgroud)
如果您想修改原始字符串而不是创建副本,可以使用std::string::insert().
std::string s = "123";
unsigned int number_of_zeros = 5 - s.length(); // add 2 zeros
s.insert(0, number_of_zeros, '0');
Run Code Online (Sandbox Code Playgroud)
结果:
00123
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65775 次 |
| 最近记录: |