博客 / 詳情

返回

C++數據格式化1 - uint轉換成字符串 & double轉換成字符串

  • 1. 關鍵詞
  • 2. strfmt.h
  • 3. strfmt.cpp
  • 4. 測試代碼
  • 5. 運行結果
  • 6. 源碼地址

1. 關鍵詞

C++ 數據格式化 字符串處理 std::string int double 跨平台

2. strfmt.h

#pragma once

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

namespace cutl
{
    /**
     * @brief Format uint64 value to a string with a given width and fill character.
     *
     * @param val the value to be formatted.
     * @param width the width of the formatted string.
     * @param fill the fill character of the formatted string, default is '0'.
     * @return std::string the formatted string.
     */
    std::string fmt_uint(uint64_t val, uint8_t width = 0, char fill = '0');
    /**
     * @brief Format double value to a string with a given precision.
     *
     * @param val the value to be formatted.
     * @param precision the precision of the formatted string, default is 2.
     * @return std::string the formatted string.
     */
    std::string fmt_double(double val, int precision = 2);
} // namespace cutl

3. strfmt.cpp

#include <sstream>
#include <iomanip>
#include <bitset>
#include "strfmt.h"

namespace cutl
{
    std::string fmt_uint(uint64_t val, uint8_t width, char fill)
    {
        std::stringstream ss;
        ss << std::setfill(fill) << std::setw(width) << val;
        return ss.str();
    }

    std::string fmt_double(double val, int precision)
    {
        std::stringstream ss;
        ss << std::setiosflags(std::ios::fixed) << std::setprecision(precision) << val;
        return ss.str();
    }
} // namespace cutl

4. 測試代碼

#include "common.hpp"
#include "strfmt.h"

void TestFormatUintAndDouble()
{
    PrintSubTitle("TestFormatUintAndDouble");

    std::cout << "fmt_uint 1: " << cutl::fmt_uint(12) << std::endl;
    std::cout << "fmt_uint 2: " << cutl::fmt_uint(12, 4) << std::endl;
    std::cout << "fmt_uint 3: " << cutl::fmt_uint(12, 4, 'x') << std::endl;
    std::cout << "fmt_double 1: " << cutl::fmt_double(3.141592653) << std::endl;
    std::cout << "fmt_double 2: " << cutl::fmt_double(3.141592653, 3) << std::endl;
}

5. 運行結果

--------------------------------------TestFormatUintAndDouble---------------------------------------
fmt_uint 1: 12
fmt_uint 2: 0012
fmt_uint 3: xx12
fmt_double 1: 3.14
fmt_double 2: 3.142

6. 源碼地址

更多詳細代碼,請查看本人寫的C++ 通用工具庫: common_util, 本項目已開源,代碼簡潔,且有詳細的文檔和Demo。

user avatar
0 位用戶收藏了這個故事!

發佈 評論

Some HTML is okay.