溫馨提示×

溫馨提示×

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

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

格式化字符串C++新方式

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

在 C++ 中,有多種方法可以格式化字符串。以下是一些建議的方法:

  1. 使用 std::ostringstream
#include <sstream>
#include <string>

int main() {
    int a = 123;
    float b = 456.789f;
    std::string s = "hello";

    std::ostringstream ss;
    ss << "整數(shù): "<< a << ", 浮點(diǎn)數(shù): "<< b << ", 字符串: " << s;
    std::string formatted_string = ss.str();

    return 0;
}
  1. 使用 std::string_format(C++20 起可用):
#include <format>
#include <string>

int main() {
    int a = 123;
    float b = 456.789f;
    std::string s = "hello";

    std::string formatted_string = std::string_format("整數(shù): {}, 浮點(diǎn)數(shù): {}, 字符串: {}", a, b, s);

    return 0;
}
  1. 使用 fmt 庫(需要安裝 fmt 庫):
#include <fmt/core.h>
#include <string>

int main() {
    int a = 123;
    float b = 456.789f;
    std::string s = "hello";

    fmt::string_view formatted_string = fmt::format("整數(shù): {}, 浮點(diǎn)數(shù): {}, 字符串: {}", a, b, s);

    return 0;
}

這些方法都可以用來格式化字符串,你可以根據(jù)自己的需求和喜好選擇合適的方法。

向AI問一下細(xì)節(jié)

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

c++
AI