Extras - C++ Code to do Various Things
Example 1 - Doing Color in
a Telnet Session
Example 2 - Inputting a Sentence
Example 3 - Print a random word from the Linux dictionary
Example 4 - Setting up a child process
Example 1 - Doing Color in a Telnet Session
These C++ escape sequences work with a telnet session to change the color of the text. The \e is an escape character (ASCII 27). You should always switch back to normal at the end of your program.
const string red
= "\e[1;31m";
//red
const string green = "\e[1;32m"; //green
const string yellow = "\e[1;33m"; //yellow
const string blue = "\e[1;34m"; //blue
const string purple = "\e[1;35m"; //purple
const string cyan = "\e[1;36m"; //cyan
const string white = "\e[1;37m"; //bright white
const string normal = "\e[0m"; //normal (grey)
Example 2 - Inputting a Sentence
When using a cin statement with a string variable, it will only take the first word --- truncates the input at the first space:
string A;
cin >> A; // The user enters "Hello World!"
cout << A; // This outputs "Hello"
The code below will allow you to input a sentence up to 70 characters:
char
Input[80];
//80 is the max number of characters
cout << "Enter a sentence: ";
cin.getline(Input, 80, '\n'); //get up to 80 chars of
input and terminate with \n
string Sentence = Input;
//declare a string variable equal to the Input array
Example 3 - Print a random word from the Linux dictionary. Remember that some of the words are proper names that begin with a capital letter.
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
#include "/home/lib/functions.h"
void main()
{
srand(time(NULL));
ifstream fin("/usr/share/dict/words");
int A = rint(45424);
string Word;
for (int x=1; x<=A; x++)
{
fin >> Word;
}
cout << Word << endl;
}
Example 4 (advanced) - Setting up a Child Process
#include <unistd.h>
#include <iostream.h>
#include <stdlib.h>
int main()
{
int child_pid;
if ((child_pid = fork()) == 0)
{
// what the child does
for (char x='a'; x<='m'; x++)
{
cout << x;
cout.flush();
sleep(1);
}
exit(0);
}
// else we are the parent
for (char x='a'; x<='z'; x++)
{
cout << x;
cout.flush();
sleep(1);
}
return 0;
}