扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

c++怎么格式化字符串

扬州沐宇科技
2024-02-27 10:53:52
c++

在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函数来格式化字符串。

扫码添加客服微信