溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

字符串格式化C++標準庫

發(fā)布時間:2024-10-09 15:01:17 來源:億速云 閱讀:78 作者:小樊 欄目:編程語言

在 C++ 中,有多種字符串格式化方法,這里介紹兩種常用的方法:std::ostringstreamstd::string::format(C++20 起可用)。

方法一:使用 std::ostringstream

std::ostringstream 是 C++ 標準庫中的一個字符串流類,可以將其他數(shù)據(jù)類型插入到字符串流中,然后將其轉(zhuǎn)換為 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;
}

以上兩種方法都可以實現(xiàn)字符串格式化,根據(jù)實際需求選擇使用即可。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

c++
AI