Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

[C++] Using C-like printf format with C++ ostream (float format sample)

50 views
Skip to first unread message

Alex Vinokur

unread,
Nov 7, 2003, 6:40:36 AM11/7/03
to
#include <cstdio>
#include <string>
#include <vector>
#include <iostream>
#include <iomanip>
using namespace std;

class set_float_format
{
private :
const size_t point_pos_;
const size_t precision_;
const size_t setw_;
const char fill_;

public :
bool check (const string& s) const
{
if (*s.begin() != '%')
{
cerr << endl
<< "ERROR-1 : "
<< "\""
<< s << "\""
<< " is invalid printf format (missing '%')"
<< endl;
return false;
}
if (*s.rbegin() != 'f')
{
cerr << endl
<< "ERROR-2 : "
<< "\""
<< s
<< "\""
<< " is invalid float format (missing 'f')"
<< endl;
return false;
}
return true;
}
set_float_format (const string& s)
:
point_pos_ (s.find('.')),
precision_ (atoi (s.substr (point_pos_ + 1, s.size() - point_pos_).c_str())),
setw_ (atoi (s.substr (1, ((point_pos_ == string::npos) ? s.size() : point_pos_) - 1).c_str())),
fill_ ((s.find ("%0") == string::npos) ? ' ' : '0')
{
if (!check(s)) exit (1);
}

friend ostream&
operator << (ostream& os, const set_float_format& format)
{
os << fixed
<< showpoint
<< setfill (format.fill_)
<< setw(format.setw_);
if (format.point_pos_ != string::npos)
{
os << noshowpoint
<< setprecision (format.precision_);
}
return os;
}
};

int main()
{
double f[] = { 0.0, 1.0, 1.2, 1.23, 1.234, 1.237, 12.3, 12345678.901 };

vector<string> format;

format.push_back ("%f");
format.push_back ("%10f");
format.push_back ("%010f");

format.push_back ("%.f");
format.push_back ("%10.f");
format.push_back ("%010.f");

format.push_back ("%.2f");
format.push_back ("%10.2f");
format.push_back ("%010.2f");

format.push_back ("%d");

for (size_t i = 0; i < format.size(); i++)
{
cout << endl;
cout << "---> Test-" << (i + 1) << " : format = " << format[i] << " <---" << endl;

cout << endl;
cout << "::: printf :::" << endl;
for (size_t k = 0; k < (sizeof(f)/sizeof(*f)); k++)
{
printf (("f[%d] = " + format[i] + "\n").c_str(), k, f[k]);
}

cout << endl;
cout << "::: cout :::" << endl;
for (size_t k = 0; k < (sizeof(f)/sizeof(*f)); k++)
{
cout << "f[" << k << "] = " << set_float_format (format[i]) << f[k] << endl;
}

cout << endl;
cout << endl;
}


return 0;
}


--
=====================================
Alex Vinokur
mailto:ale...@connect.to
http://mathforum.org/library/view/10978.html
news://news.gmane.org/gmane.comp.lang.c++.perfometer
=====================================


0 new messages