温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

字符串格式化C++标准库

发布时间:2024-10-09 15:01:17 来源:亿速云 阅读:78 作者:小樊 栏目:编程语言

在 C++ 中,有多种字符串格式化方法,这里介绍两种常用的方法:std::ostringstreamstd::string::format(C++20 起可用)。

方法一:使用 std::ostringstream

std::ostringstream 是 C++ 标准库中的一个字符串流类,可以将其他数据类型插入到字符串流中,然后将其转换为 std::string 类型。

示例代码:

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

int main() {
    int age = 25;
    std::string name = "Tom";

    std::ostringstream oss;
    oss << "My name is " << name << ", and I am " << age << " years old.";

    std::string message = oss.str();
    std::cout << message << std::endl;

    return 0;
}

方法二:使用 std::string::format(C++20)

std::string::format 是 C++20 标准库中新增的字符串格式化方法,类似于 Python 的 str.format 方法。

示例代码:

#include <iostream>
#include <string>

int main() {
    int age = 25;
    std::string name = "Tom";

    std::string message = std::string::format("My name is %s, and I am %d years old.", name.c_str(), age);
    std::cout << message << std::endl;

    return 0;
}

以上两种方法都可以实现字符串格式化,根据实际需求选择使用即可。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI