前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++字符串格式化

C++字符串格式化

作者头像
用户7886150
修改2021-02-19 15:37:23
8230
修改2021-02-19 15:37:23
举报
文章被收录于专栏:bit哲学院

参考链接: C++ vswprintf()

// iniconfig.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"

#include <windows.h>

#include <string>

#include <iostream>

#include <sstream>

using namespace std;

std::string & std_string_format(std::string & _str, const char * _Format, ...) 

{

    std::string tmp;

    va_list marker = NULL;

    va_start(marker, _Format);

    size_t num_of_chars = _vscprintf(_Format, marker);

    if (num_of_chars > tmp.capacity()) {

        tmp.resize(num_of_chars + 1);

    }

    vsprintf_s((char *)tmp.data(), tmp.capacity(), _Format, marker);

    va_end(marker);

    _str = tmp.c_str();

    return _str;

}

std::wstring & std_wstring_format(std::wstring & _str, const wchar_t * _Format, ...)

{

    std::wstring tmp;

    va_list marker = NULL;

    va_start(marker, _Format);

    size_t num_of_chars = _vscwprintf(_Format, marker);

    if (num_of_chars > tmp.capacity()) {

        tmp.resize(num_of_chars + 1);

    }

    vswprintf_s((wchar_t *)tmp.data(), tmp.capacity(), _Format, marker);

    va_end(marker);

    _str = tmp.c_str();

    return _str;

}

int main()

{

    int num = 1234;

    double dnum = 8832.234;

    string strResult;

    string format = "the num is %d,the dnum is %f";

    string ret = std_string_format(strResult, format.c_str(), num, dnum);

    wstring strResult2;

    wstring format2 = L"the num is %d,the dnum is %f";

    wstring ret2 = std_wstring_format(strResult2, format2.c_str(), num, dnum);

    //使用ostringstream格式化字符串

    ostringstream ss;

    ss << "the num is " << num << ",the dnum is " << dnum;

    string strResult3 = ss.str();

    wstringstream ws;

    ws << L"the num is " << num << L",the dnum is " << dnum;

    wstring strResult4 = ws.str();

    return 0;

}

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档