Chapter 21 More Input / Output

21.1  Set the number of digits after decimal point

The number of digits past the decimal can be set using the iomanip library.  The program below rounds the output to two decimal places.
 

Program 21.1 - Windows.h colors

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

int main ()
{
   float A=12.526, B=.009, C=1.2;
   cout << fixed << setprecision(2);
   cout << A << "   " << B << " " << C << endl;
   return 0;
}

Output
12.53  0.01  1.20


21.2  Color in Code::Blocks Console Program

If you are doing a console program in Code::Blocks using Windows, then you can change the color of the text using the windows.h library.  If you are using a black background, I recommend using colors 7,  10, 11, 12, 13, 14, and 15.  Blue and gray are dark and hard to see.
 

Program 21.2 - Windows.h colors

#include <iostream>
#include <windows.h>
using namespace std;

int main()
{
   HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);

   SetConsoleTextAttribute(h, 7);
   cout << "Color 7 is the default white\n";
   SetConsoleTextAttribute(h, 8);
   cout << "Color 8 is gray\n";
   SetConsoleTextAttribute(h, 9);
   cout << "Color 9 is blue\n";
   SetConsoleTextAttribute(h, 10);
   cout << "Color 10 is green\n";
   SetConsoleTextAttribute(h, 11);
   cout << "Color 11 is cyan\n";
   SetConsoleTextAttribute(h, 12);
   cout << "Color 12 is red\n";
   SetConsoleTextAttribute(h, 13);
   cout << "Color 13 is purple\n";
   SetConsoleTextAttribute(h, 14);
   cout << "Color 14 is yellow\n";
   SetConsoleTextAttribute(h, 15);
   cout << "Color 15 is bright white\n";
   return 0;
}
 

Output


After color 15 are the inverse colors.  The screen print below shows all the colors from 1 - 254.


 


21.3  Sound in Code::Blocks Console Program

If you are doing a console program in Code::Blocks using Windows, you can play a wav (not mp3) file as shown below.  The cricket.wav file must be in the same folder as your exe - it is not embedded into the exe.  You must first make a change in the Code::Blocks settings:   Select Settings, Compiler, Linker settings.  Under Other linker options, paste the following:  -lwinmm

Program 21.3 - Code::Blocks sound

// Paste this under Settings->Compiler->Linker settings->Other linker options: -lwinmm
#include <iostream>
#include <windows.h>
#include <mmsystem.h>
using namespace std;

int main()
{
  
// cricket.wav must be in the same folder at the cpp and exe
   mciSendString("open cricket.wav alias MY_SND3", NULL, 0, NULL);
   mciSendString("play MY_SND3", NULL, 0, NULL);
   system("pause");
// pause program because sound stops when program ends
}

Output
12.53  0.01  1.20