가장 간단한 방법은처럼 출력 스트림에()는 표준 : 이제 stringstream로 ""가치를 작성하고 그 결과 STR을 작성하는 것입니다 :
std::stringstream ss;
ss << " " << iBytes;
cout << "bytes " << setw(20) << ss.str() << endl;
그리고 여기에 전체 과잉 온다. 접두사가 붙은 템플릿 클래스로, 두 개의 생성자 인수 prefix,val
을 하나의 문자열로 묶어 인쇄 할 수 있습니다. 숫자 형식이며, 정밀도는 최종 출력 스트림에서 가져옵니다. ints, float, strings 및 const char *와 작동합니다. 그리고 유효한 출력 연산자를 가진 모든 arg를 사용해야합니다.
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;
template<class T>
class prefixed_base {
public:
prefixed_base(const std::string & prefix,const T val) : _p(prefix),_t(val) {
}
protected:
std::string _p;
T _t;
};
// Specialization for const char *
template<>
class prefixed_base<const char*> {
public:
prefixed_base(const std::string & prefix,const char * val) : _p(prefix),_t(val) {
}
protected:
std::string _p;
std::string _t;
};
template<class T>
class prefixed : public prefixed_base<T> {
private:
typedef prefixed_base<T> super;
public:
prefixed(const std::string & prefix,const T val) : super(prefix,val) {
}
// Output the prefixed value to an ostream
// Write into a stringstream and copy most of the
// formats from os.
std::ostream & operator()(std::ostream & os) const {
std::stringstream ss;
// We 'inherit' all formats from the
// target stream except with. This Way we
// keep informations like hex,dec,fixed,precision
ss.copyfmt(os);
ss << std::setw(0);
ss << super::_p;
ss.copyfmt(os);
ss << std::setw(0);
ss << super::_t;
return os << ss.str();
}
};
// Output operator for class prefixed
template<class T>
std::ostream & operator<<(std::ostream & os,const prefixed<T> & p) {
return p(os);
}
// This function can be used directly for output like os << with_prefix(" ",33.3)
template<class T>
prefixed<T> with_prefix(const std::string & p,const T v) {
return prefixed<T>(p,v);
}
int main() {
int iBytes = 123981;
int iTotalBytes = 1030131;
cout << setfill('.');
cout << right;
cout << "bytes " << setw(20) << with_prefix(" ",iBytes) << endl;
cout << "total bytes " << setw(14) << with_prefix(" ",iTotalBytes) << endl;
cout << "bla#1 " << setw(20) << std::fixed << std::setprecision(9) << with_prefix(" ",220.55) << endl;
cout << "blablabla#2 " << setw(14) << std::hex << with_prefix(" ",iTotalBytes) << endl;
}
감사합니다, 나는 다른 방법이 없다는 것을 두려워하지만. 어느 누구도 아이디어를 생각해 내지 않으면 (과잉 살상) 나는 당신의 해결책을 받아 들일 것입니다. 유니 코드 지원이 필요하다는 것을 잊어 버렸지 만, 그것은 실제로 문제가 아닙니다. – seizu
@seizu 더 많은 템플릿 마법이 필요합니다. ostream을 basic_ostream 및 basic_string 등으로 변환하거나 간단한 문자열 스트림 솔루션으로 이동하십시오. –
Oncaphillis