내밥줄/프로그래밍

[펌]stringstream을 이용한 문자열의 형식화

jjoell 2009. 3. 19. 18:49

1. 스트림의 형식화를 위한 manipulator는 ipmanip에 정의되어 있다.

2. stringstream을 문자열을 형식화 하기 위한 출력스트림으로 이용하고 str()멤버를 통해서 string을 얻어서 사용할 수 있다.

#include <iostream>
#include <sstream>
#include <string>
#include <iomanip>
#include <atlbase.h>
using namespace std;
void makeFileName (const CComBSTR &bstrPath, const CComBSTR &bstrPrefix)
{
        wstringstream fname;
        wstring wstrIndexFileName, wstrDataFileName;

fname << (BSTR)bstrPath << L"\\" << (BSTR)bstrPrefix << setfill(L'0')
              << L"_" << setw(4) << (int)2005 << setw(2) << (int)1 << setw(2) << (int)1
              << L"_" << setw(4) << (int)2005 << setw(2) << (int)12 << setw(2) << (int)31
              << L"_" << setw(4) << (int)1;

                // setw와 setfill로 너비와 채움문자를 설정해서 날짜값을 형식화 한다.
        wstrIndexFileName = fname.str() + L".log";
        wstrDataFileName = fname.str() + L".dat";

                // 문자열에 대한 + operator 테스트. 
        wprintf(L"IndexFileName : %s\n", wstrIndexFileName.c_str());
        wprintf(L"DataFileName : %s\n", wstrDataFileName.c_str());
}
void main(void)
{
        makeFileName(L"C:\\temp", L"MessageLog");

                // CComBSTR의 임시객체가 생성되에서 makeFileName에 전달된다.
}

=============== Output =================

IndexFileName : C:\temp\MessageLog_20050101_20051231_0001.log
DataFileName : C:\temp\MessageLog_20050101_20051231_0001.dat


출처:http://manylee.tistory.com/49?srchid=BR1http%3A%2F%2Fmanylee.tistory.com%2F49