Linux 拨号vps windows公众号手机端

c++怎么格式化字符串

lewis 9年前 (2016-12-23) 阅读数 6 #程序编程
文章标签 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函数来格式化字符串。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门