C++/Console/cout custom

Материал из C\C++ эксперт
Перейти к: навигация, поиск

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

<source lang="cpp">

  1. include <iostream>
  2. 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;

}

      </source>


A simple output manipulator: sethex

<source lang="cpp">

  1. include <iostream>
  2. 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;

}


      </source>


Create an output manipulator.

<source lang="cpp">


  1. include <iostream>
  2. 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; 

}

      </source>


Create custom output format

<source lang="cpp">

  1. 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;

}

      </source>


Custom cout output manipulator

<source lang="cpp">

  1. 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;

}


      </source>


Define operator for cout

<source lang="cpp">

  1. include <iostream>
  2. 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;

}


      </source>