C++/Console/cout custom

Материал из C\C++ эксперт
Версия от 10:27, 25 мая 2010; Admin (обсуждение | вклад) (1 версия: Импорт контента...)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

A manipulator: turns on the showbase flag and sets output to hexadecimal

#include <iostream>
#include <iomanip>
using namespace std;
ostream &sethex(ostream &stream)
{
  stream.setf(ios::showbase);
  stream.setf(ios::hex, ios::basefield);
  return stream;
}
int main()
{
  cout << 256 << " " << sethex << 256;
  return 0;
}


A simple output manipulator: sethex

#include <iostream>
#include <iomanip>
using namespace std;

ostream &sethex(ostream &stream)
{
  stream.setf(ios::showbase);
  stream.setf(ios::hex, ios::basefield);
  return stream;
}
int main()
{
  cout << 256 << " " << sethex << 256;
  return 0;
}


Create an output manipulator.

 
#include <iostream> 
#include <iomanip> 
using namespace std; 
 
ostream &setup(ostream &stream) 
{ 
  stream.setf(ios::left); 
  stream << setw(10) << setfill("$"); 
  return stream; 
} 
 
int main() 
{ 
  cout << 10 << " " << setup << 10; 
 
  return 0; 
}


Create custom output format

#include <iostream>
using namespace std;
ostream &setup(ostream &stream)
{
  stream.width(10);
  stream.precision(4);
  stream.fill("*");
  return stream;
}
int main()
{
  cout << setup << 123.123456;
  return 0;
}


Custom cout output manipulator

#include <iostream>
using namespace std;
// Attention:
ostream &atn(ostream &stream)
{
  stream << "Attention: ";
  return stream;
}
// Please note:
ostream &note(ostream &stream)
{
  stream << "Please Note: ";
  return stream;
}
int main()
{
  cout << atn << "High voltage circuit\n";
  cout << note << "Turn off all lights\n";
  return 0;
}


Define operator for cout

#include <iostream>
#include <iomanip>
using namespace std;
ostream &ra(ostream &stream)
{
  stream << "--> ";
  return stream;
}
ostream &la(ostream &stream)
{
  stream << " <--";
  return stream;
}
int main()
{
  cout << "AAA" << ra << 33.23 << endl;
  cout << "BBB" << ra << 67.66 << la;
  return 0;
}