问题描述
||
我想在字符串中添加前导零的变量。
我没有在Google上找不到任何东西,而没有人提及printf,
但是我想在没有(s)printf的情况下执行此操作。
读者中有人知道吗?
解决方法
// assuming that `original_string` is of type `std:string`:
std::string dest = std::string( number_of_zeros,\'0\').append( original_string);
,如果您想要一个n_zero零的字段,我可以提供这种单行解决方案:
std::string new_string = std::string(n_zero - old_string.length(),\'0\') + old_string;
例如:
old_string = \“ 45 \”; n_zero = 4;
new_string = \“ 0045 \”;
,您可以在流操纵器中使用std::string::insert
,ѭ3use或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;
}
,您可以执行以下操作:
std::cout << std::setw(5) << std::setfill(\'0\') << 1;
这应该打印00001
。
但是请注意,填充字符为\“ sticky \”,因此在完成使用零填充的操作后,必须使用ѭ7才能再次获得通常的行为。
,使用setw,ios_base :: width和setfill的C ++方法
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int a = 12;
const int b = 6;
cout << setw(width) << row * col;
cout << endl;
return 0;
}
,这对我来说很好。您无需将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();
}
,memcpy(target,\'0\',sizeof(target));
target[sizeof(target)-1] = 0;
然后,在缓冲区末尾添加您想要零开头的任何字符串。
如果是整数,请记住remember11ѭ(又名ln(number)/ln(10)+1
)为您提供数字的长度。
,一行,但限于整数和最大6个零:
int number = 42;
int leading = 3; //6 at max
std::to_string(number*0.000001).substr(8-leading); //=\"042\"
运行