Notice»

Recent Post»

Recent Comment»

Recent Trackback»

Archive»

« 2024/3 »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

기본 사용법

CString
CString str;
str.Format("%s%03d", szSomeVar, nSomeVar);

타입 안정성을 중요시하는 C++ 에서는 안타깝게도 CString의 Format 계열 함수가 제공 되지 않는다.
그래서 버퍼를 잡아 C의 런타임함수인 sprintf 함수를 사용하는수 밖에 없다.
그러나 C++에서는 stream 객체가 있으므로 sprintf 보다 우아(?) 하게 사용 할수 있다.

#include <sstream>로 사용할수 있으며 input/output/ input&output 버전이 따로 존재한다.

stringstream  in & out
ostringstream out
istringstream in

유니 코드 버전은 위의 클래스 네임에 w만 앞쪽에 붙여 주면되고
stringstream 내의 함수 중에 str() 멤버 함수로 string 클래스의 객체와 같이 연동해서 쓸 수 있다.

STL
#include <string>
#include <sstream>
#include <iomanip>
 
using namespace std;
ostringstream strStream;
strStream << szSomeVar << setw(3) << setfill('0') << nSomeVar;
string str = strStream.str();

BOOST
#include <boost/format.hpp>
#include <string>
 
std::string someString;
someString = boost::str(boost::format("%s%03d") % szSomeVar % nSomeVar);

CString의 Format에 해당하는 STL 코드와 BOOST 코드


직접 구현하기

1. 코드프로젝트
STL Format

CString의 Format같은 기능을 함수로 구현해 놓은게 있다.
근데 VC6에선 제대로 컴파일이 안된다. 우선 string의 clear는 stlport에는 없다.

2. 권진호님
sprintf 와 string 과의 만남

3. codein.co.kr

#define _MAX_CHARS 8000

int Format(std::string& txt, const TCHAR* szFormat,...)

{ 

    std::vector<TCHAR> _buffer(_MAX_CHARS);

    va_list argList;

    va_start(argList,szFormat);

#ifdef _UNICODE

    int ret = _vsnwprintf(&_buffer[0],_MAX_CHARS,szFormat,argList);

#else

    int ret = _vsnprintf(&_buffer[0],_MAX_CHARS,szFormat,argList);

#endif

    va_end(argList);

    txt.assign(&_buffer[0],ret);

    return ret;

}


4. 본인은 CString의 FromatV함수로 간단히 구현했음.  차라리 CString을 사용하는게 낫지 않냐고 하시면..
내부 구현은 나중에 제대로 테스트후 적용해도 된다. ㅋ

UINT StrPrintf( string& rstr, const char *pFmt, ...  )

    va_list args;
    va_start(args, pFmt);
   
    CString csMsg;
    csMsg.FormatV(pFmt, args);
    rstr = csMsg;
   
    va_end(args);
    return rstr.length();
}


'프로그래밍 > C, C++' 카테고리의 다른 글

boost  (0) 2009.09.25
stringstream 을 사용한 파일 읽기 사용 예제  (0) 2009.05.12
ASCII 문자 코드  (0) 2009.04.15
STLport 설치 및 사용 For VC6  (0) 2009.04.06
: