Program: Displaying colours and special characters



STOP PRESS! The full book is now available DIRECTLY from Amazon with lower shipping costs!

This program uses an infinite  while  loop to produce a rolling display of owls.


Owls? Yes, owls. Admittedly, they look a bit more like parrots, but times are hard.


Each, erm... owl is displayed using several  cout  statements. Remember that the  \  backslash character in C++ is used to precede one or more "special" characters, such as  \n  for newline\t  for tab or  \e  for an escape-sequence. To display a backslash character, it is necessary to use the  \\  double-backslash.



Select and copy the C++ source-code at the bottom of this post.

Paste into a text editor, such as Nano or Geany.


Then save the new file, ending in .cpp


I used owls.cpp


To compile from the command-line:


    g++ -o owls.cpp owls


To run from the command-line:


    ./owls






Code is below...



#include <iostream>  // For screen output
#include <unistd.h>  // For sleep function to pause program



using namespace std; // Standard identifer names for cout and endl


int main()
{

    // Handy identifiers for ANSI colour escape sequences
    string YELLOW = "\e[33m";
    string GREEN = "\e[32m";
    string WHITE = "\e[0m";



    // Infinite while loop
    while ( true )
    {

        // Top of head is green
        cout << GREEN;
        cout << " +-----+ " << endl;
        cout << " | ";



        // White eyes
        cout << WHITE;
        cout << "O O";



        // More of body, green
        cout << GREEN;
        cout << " |" << endl;
        cout << "/|  ";



        // Yellow beak
        cout << YELLOW;
        cout << "v";



        // Rest of body is green
        cout << GREEN;
        cout << "  |\\" << endl;
        cout << "/|     |\\" << endl;



        // Feet
        cout << " +-";
        cout << YELLOW;
        cout << "+";
        cout << GREEN;
        cout << "-";
        cout << YELLOW;
        cout << "+";
        cout << GREEN;
        cout << "-+" << endl;



        // Wait 3 seconds before next owl
        sleep(3);



    }  // end of while loop


    return 0;
}



Find out more - buy the book on Amazon...