Wednesday, 15 June 2011

How can I easily format my data table in C++? -



How can I easily format my data table in C++? -

i'm not sure, think remember there beingness in java can specify how far left of window string or digit begins..

how format table? have (using setw):

bob doe 10.96 7.61 14.39 2.11 47.30 14.21 44.58 5.00 60.23 helen city 10.44 7.78 16.27 1.99 48.92 13.93 53.79 5.00 70.97 joe greenish 10.90 7.33 14.49 2.05 47.91 14.15 44.45 4.70 73.98

and ideally like:

bob doe blr 10.96 7.61 14.39 2.11 47.30 14.21 44.58 5.00 60.23 4:27.47 helen city cub 10.90 7.33 14.49 2.05 47.91 14.15 44.45 4.70 73.98 4:29.17 joe greenish usa 10.44 7.78 16.27 1.99 48.92 13.93 53.79 5.00 70.97 5:06.59

is way calculations? or there magical more simple way?

in c++, have 3 functions help want. there defined in <iomanip>. - setw() helps defined width of output. - setfill() fill rest character want (in case ' '). - left (or right) allow define alignment.

here code write first line :

#include <iostream> #include <iomanip> using namespace std; int main() { const char separator = ' '; const int namewidth = 6; const int numwidth = 8; cout << left << setw(namewidth) << setfill(separator) << "bob"; cout << left << setw(namewidth) << setfill(separator) << "doe"; cout << left << setw(numwidth) << setfill(separator) << 10.96; cout << left << setw(numwidth) << setfill(separator) << 7.61; cout << left << setw(numwidth) << setfill(separator) << 14.39; cout << left << setw(numwidth) << setfill(separator) << 2.11; cout << left << setw(numwidth) << setfill(separator) << 47.30; cout << left << setw(numwidth) << setfill(separator) << 14.21; cout << left << setw(numwidth) << setfill(separator) << 44.58; cout << left << setw(numwidth) << setfill(separator) << 5.00; cout << left << setw(numwidth) << setfill(separator) << 60.23; cout << endl; cin.get(); }

edit : cut down code, can utilize template function :

template<typename t> void printelement(t t, const int& width) { cout << left << setw(width) << setfill(separator) << t; }

that can utilize :

printelement("bob", namewidth); printelement("doe", namewidth); printelement(10.96, numwidth); printelement(17.61, numwidth); printelement(14.39, numwidth); printelement(2.11, numwidth); printelement(47.30, numwidth); printelement(14.21, numwidth); printelement(44.58, numwidth); printelement(5.00, numwidth); printelement(60.23, numwidth); cout << endl;

c++

No comments:

Post a Comment