https://rentry.org/PPP2_p387

// Code derived from Stroustrup's PPP2 book
// § 11.2.5 Fields
//  -and beginning on p 387

#include <iomanip>
#include <iostream>

using namespace std;

int main() {
  cout << 123456  // no field used
       << '|' << setw(4) << 123456
       << '|'                       // 123456 doesn’t fit in a 4-char field
       << setw(8) << 123456 << '|'  // set field width to 8
       << 123456 << "|\n";          // field sizes don’t stick

  //---
  cout << '\n';

  cout << 12345 << '|' << setw(4) << 12345 << '|' << setw(8) << 12345 << '|'
       << 12345 << "|\n";
  cout << 1234.5 << '|' << setw(4) << 1234.5 << '|' << setw(8) << 1234.5 << '|'
       << 1234.5 << "|\n";
  cout << "asdfg" << '|' << setw(4) << "asdfg" << '|' << setw(8) << "asdfg"
       << '|' << "asdfg"
       << "|\n";
}

build & run:

g++ -std=c++20 -O2 -Wall -pedantic ./ch_11/main_p387.cpp && ./a.out

PrevUpNext

Edit
Pub: 09 Apr 2023 05:07 UTC
Views: 527