溫馨提示×

c++怎么格式化字符串

c++
小億
287
2024-02-27 10:53:52
欄目: 編程語言

在C++中,可以使用std::stringstream或者printf函數來格式化字符串。

使用std::stringstream

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    int num = 10;
    float f = 3.14;
    std::string str = "Hello";

    ss << "Number: " << num << ", Float: " << f << ", String: " << str;

    std::string formatted_str = ss.str();
    std::cout << formatted_str << std::endl;

    return 0;
}

使用printf函數:

#include <iostream>
#include <cstdio>

int main() {
    int num = 10;
    float f = 3.14;
    std::string str = "Hello";

    char buffer[100];
    std::sprintf(buffer, "Number: %d, Float: %.2f, String: %s", num, f, str.c_str());

    std::string formatted_str = buffer;
    std::cout << formatted_str << std::endl;

    return 0;
}

這樣就可以通過std::stringstream或者printf函數來格式化字符串。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女