I am learning C++. cout
is an instance of std::ostream
class.
How can I print a formatted string with it?
I can still use printf
Field Width
Setting field width is very simple. For each variable, simply precede it with "setw(n)". Like this:
#include
#include using namespace std; int main() { const int max = 12; const int width = 6; for(int row = 1; row <= max; row++) { for(int col = 1; col <= max; col++) { cout << setw(width) << row * col; } cout << endl; } return 0; } Notice how "setw(n)" controls the field width, so each number is printed inside a field that stays the same width regardless of the width of the number itself.
-- From "Programming/C++ tutorial" by P. Lutus.