字符串前面自动补零?

vastsky 2002-04-22 11:59:37
str="2";
我想让str不足3位时,前面自动补零成002,该怎么做
...全文
3812 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
babysloth 2002-04-22
  • 打赏
  • 举报
回复
sprintf是一种做法。
在C++标准库里,格式化属于IOStream的职责。如果想要更好的弹性,就可以像IOStream求助。

#include <sstream>
#include <iomanip>
#include <iostream>

int main()
{
using namespace std;
stringstream inter;
string s = "12";
inter << setw(3) << setfill('0') << s;
inter >> s;
cout << s << endl;
return 0;
}

可以设置填充宽度、字符及位置。
如果经常用,不妨写个包装函数。

#include <iomanip>
#include <iostream>

template <typename T, typename S>
T fill_cast(const S& v, const int width, const char c)
{
T result;
std::stringstream inter;
inter << std::setw(width) << std::setfill(c) << v;
inter >> result;
return result;
}

int main()
{
std::string s = "12";
std::cout << fill_cast<std::string>(s, 3, '0') << std::endl;
return 0;
}

garfield_82 2002-04-22
  • 打赏
  • 举报
回复
如果你有boost,可以这样: Vc6+Win200Professional [O]

# include <iostream>
# include <iomanip.h>
# include <string>
# include <boost/lexical_cast.hpp>



int main ()
{

int i ;
std :: string str = "2";
i = boost :: lexical_cast <int> ( str );

std :: cout.width ( 3 );
std :: cout.setf ( ios::right, ios ::adjustfield );
std :: cout.fill ( '0' );
std :: cout << i << std :: endl;
return 0;
}
晨星 2002-04-22
  • 打赏
  • 举报
回复
楼顶是对的。
其实用sprintf也一样。
sprintf(str , "%3d" , atoi(str));
其实你既然用的是整数,为什么不直接:
sprintf(str , "%3d" , 2)呢?转过来转过去的多麻烦!
chijiao 2002-04-22
  • 打赏
  • 举报
回复
like that:
CString str;
str = "2";
str.Format("%03d",atoi((char*)str));
ynli2002 2002-04-22
  • 打赏
  • 举报
回复
做一个小函数不就可以了吗

70,007

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧