Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c++ 格式化字符串

作者:风外听竹   发布日期:2025-04-09   浏览:105

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

// 使用 std::ostringstream 和 std::setw 来格式化字符串
std::string formatString(int number, int width) {
    std::ostringstream oss;
    // 设置输出宽度,并在前面填充空格
    oss << std::setw(width) << std::setfill(' ') << number;
    return oss.str();
}

// 使用 std::string 的 format 方法(C++20)
std::string formatStringC20(const std::string& format, int value) {
    return std::format(format, value);
}

int main() {
    int num = 42;
    int width = 10;

    // 示例 1: 使用 ostringstream 格式化字符串
    std::string formatted1 = formatString(num, width);
    std::cout << "Using ostringstream: '" << formatted1 << "'" << std::endl;

    // 示例 2: 使用 C++20 的 std::format
    std::string formatted2 = formatStringC20("The answer is {}", num);
    std::cout << "Using C++20 std::format: " << formatted2 << std::endl;

    return 0;
}

解释说明

  1. 使用 std::ostringstreamstd::setw:

    • std::ostringstream 是一个输出字符串流,可以用来构建和格式化字符串。
    • std::setw(width) 设置输出的最小宽度,如果实际内容小于这个宽度,则用指定字符(默认是空格)填充。
    • std::setfill(' ') 设置填充字符为 ' '
  2. 使用 C++20 的 std::format:

    • C++20 引入了 std::format 函数,类似于 Python 的 str.format,可以更方便地格式化字符串。
    • std::format("The answer is {}", num) 中的 {} 是占位符,会被 num 替换。

这两个示例展示了如何在 C++ 中格式化字符串,分别使用了传统的流操作和新的 C++20 特性。

上一篇:c++ hash

下一篇:mqtt c++

大家都在看

c++闭包

c++单引号和双引号的区别

c++ 注释

c++如何判断素数

c++freopen怎么用

c++ 获取系统时间

c++进制转换函数

c++ tcp

c++ gcd函数

c++ cli

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站