在C ++中格式化整数 [英] Formatting an integer in C++

查看:133
本文介绍了在C ++中格式化整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个8位整数,我想要打印格式如下:

I have an 8 digit integer which I would like to print formatted like this:

XXX-XX-XXX

XXX-XX-XXX

我想使用一个函数接受一个int并返回一个字符串。

I would like to use a function that takes an int and returns a string.

这是一个很好的方法?

推荐答案

这是我个人的做法。可能不是解决问题的最快方式,绝对不像egrunin的功能可重复使用,但它打击我,既干净又容易理解。我会把它放在戒指中作为mathier和loopier解决方案的替代。

This is how I'd do it, personally. Might not be the fastest way of solving the problem, and definitely not as reusable as egrunin's function, but it strikes me as both clean and easy to understand. I'll throw it in the ring as an alternative to the mathier and loopier solutions.

#include <sstream>
#include <string>
#include <iomanip>

std::string format(long num) {
  std::ostringstream oss;
  oss << std::setfill('0') << std::setw(8) << num;
  return oss.str().insert(3, "-").insert(6, "-");
};

这篇关于在C ++中格式化整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆