1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
|
#include <iostream>
#include <string>
#include <format> // C++20
void show_items( const std::string id[], const std::string name[],
const double price[], const int qty[], std::size_t num_items )
{
if( num_items == 0 )
{
std::cout << "there are no records\n" ;
return ;
}
// https://en.cppreference.com/w/cpp/utility/format/format
// https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification
static const std::string_view hdr_fmt = "{: ^10}{: ^40}{: >10}{: >5}" ;
static const std::string_view item_fmt = "{: ^10}{: ^40}{: >10.2f}{: >5}" ;
std::cout << std::format( hdr_fmt, "id", "name", "price", "qty" ) << '\n' // print header
<< std::string( 65, '-' ) << '\n' ;
for( std::size_t i = 0 ; i < num_items ; ++i ) // print each item
std::cout << std::format( item_fmt, id[i], name[i], price[i], qty[i] ) << '\n' ;
}
int main()
{
const std::string id[100] { "abcd", "efghij" } ;
const std::string name[100] { "ABcdefgh12345", "IJjklmnopqrst6789" } ;
const double price[100] { 12.345, 678.98765 } ;
const int qty[100] { 22, 56 } ;
std::size_t n_items = 2 ;
show_items( id, name, price, qty, n_items ) ;
}
|