防止溢出的stringsprintf

由于WINCE不支持 _vscwprintf() 所以在使用字符串时候溢出是个大问题,当然如果可以忍受 stringstream的话,这个就不是问题了,对于习惯使用sprintf或者MFC中CString的Format的人们来说无疑是很郁闷的;

 

stringstream格式化输出可以采用如下操作

    ostringstream   ostr;   
    ostr << "sdfsaf" << "afsa";
    string sp = ostr.str();

 

 

下面介绍一下stringsprintf, stringsprintf是参考他人的劳动成果所作的修改,主要改动就是改成了模板;

////////////////////////////////////////////stringsprintf.h//////////////////////////////////////////////

 

#include <cstdarg>
#include <sstream>
#include <string>

using namespace std;


template<typename _U>
basic_string<_U, char_traits<_U>, allocator<_U> > & stringprintf( basic_string<_U, char_traits<_U>, allocator<_U> > &s, const _U *fmt, ... )
{
    s.clear();
   //assert( s.empty() );

    va_list ap;
    va_start(ap, fmt);
    const _U *next_c; // next character
    while ( *fmt != _T('/0') )
    {
        switch ( *fmt )
        {
            case _T('%'):
            {
                next_c = fmt + 1;
                switch ( *next_c )
                {
                    case _T('/0'):
                        s += *fmt;
                        break;
                    case _T('%'):
                        s += _T('%');
                        ++fmt;
                        break;
                    case _T('s'):
                        s += va_arg(ap, _U*);
                        ++fmt;
                        break;
                    case _T('d'):                   
                    {
                        basic_ostringstream<_U, char_traits<_U>,allocator<_U> > oss;
                        oss << va_arg(ap, int);
                        s += oss.str();
                        ++fmt;
                        break;
                    }
                    case _T('u'):                   
                    {
                        basic_ostringstream<_U, char_traits<_U>,allocator<_U> > oss;
                        oss << va_arg(ap, unsigned int);
                        s += oss.str();
                        ++fmt;
                        break;
                    }
                    case _T('f'):
                    {
                        basic_ostringstream<_U, char_traits<_U>,allocator<_U> > oss;
                        oss << va_arg(ap, double);
                        s += oss.str();
                        ++fmt;
                        break;
                    }
                    default:
                        assert( !_T("format unsupported.") );
                        break;
                }

                break;
            }
            default:
                s += *fmt;
                break;
        }

        ++fmt;
    }
    va_end(ap);

    return s;
}

你可能感兴趣的:(String,list,basic,mfc,character,WinCE)