在C ++中格式化整数

编程入门 行业动态 更新时间:2024-10-27 07:28:32
本文介绍了在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 ++中格式化整数

本文发布于:2023-05-28 12:27:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/320876.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!