C++/Console/cout width
Содержание
cout: width(), precision(), and fill().
#include <iostream>
using namespace std;
int main()
{
cout.setf(ios::showpos);
cout.setf(ios::scientific);
cout << 123 << " " << 123.23 << endl;
cout.precision(2); // two digits after decimal point
cout.width(10); // in a field of 10 characters
cout << 123 << " ";
cout.width(10); // set width to 10
cout << 123.23 << endl;
cout.fill("#"); // fill using #
cout.width(10); // in a field of 10 characters
cout << 123 << " ";
cout.width(10); // set width to 10
cout << 123.23;
return 0;
}
Create a table of log10 and log from 2 through 100.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double x;
cout.precision(5);
cout << " x log x ln e\n\n";
for(x = 2.0; x <= 100.0; x++) {
cout.width(10);
cout << x << " ";
cout.width(10);
cout << log10(x) << " ";
cout.width(10);
cout << log(x) << "\n";
}
return 0;
}
Left-justification and right-justification.
#include <iostream>
#include <iomanip>
using std::cout;
using std::endl;
using std::ios;
using std::setw;
using std::setiosflags;
using std::resetiosflags;
int main()
{
int x = 12345;
cout << "Default is right justified:\n"
<< setw(10) << x << "\n\nUsing Member Functions"
<< "\nUse setf to set ios::left:\n" << setw(10);
return 0;
}
Set cout length
#include <iostream>
#include <cstring>
using namespace std;
void center(char *s);
int main()
{
center("www.java2s.com!");
center("www.java2s.com");
return 0;
}
void center(char *s)
{
int len;
len = 40+(strlen(s)/2);
cout.width(len);
cout << s << "\n";
}