convert integer to any base C++

this function is capable of converting integers to any base format 2-16. this includes binary, octal, and hexadecimal. adding larger bases is as simple as lengthening the alpha string.

//this recursive base converter is valid for base 2~16
void Converter::toBase(int n, int base)
{
    	string alpha="0123456789ABCDEF";
    	if (n > 0)
        	{
        		toBase(n/base,base);
        		cout << alpha[n%base];
        	}
}

Some Great Examples of recursion C++

This little program demonstrates the recursion technique in three different settings.  It includes recursive algorithms to search an array, reverse a number, and find the greatest common divisor of two numbers.

// Boyd Turley
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip> //required to use setw()
#include <cstdio>

using namespace System;
using namespace std;
///////////////////////////////////// Globals
const int TABLE_ROWS = 30;
const int TABLE_COLS = 20;
int table[TABLE_COLS][TABLE_ROWS];
int grid[599];

//////////////////////////////////// FXN Defs.
bool posWhole(int checkme);

void NumReverse(int reverseme);

void setOrder(int num1, int num2);

int GCD(int num1, int num2);

void gridSearch();

///////////////////////////////////////////////////////////////////////////////////////// MAIN
int main(array<System::String ^> ^args)
{
	char thechoice = 0;

		while(thechoice != '!')
		{
			system("cls");
			cout << "Recursion Menu:"<<endl
			 << "S.  Search an array for a number." << endl
			 << "M. Mirror a number." << endl
			 << "G. Greatest Common Devisor." << endl
			 << "Q. Quit Program." << endl;
			cin >> thechoice;

		switch(thechoice)
		{
			int num;
			case 'S':
			case 's':
				{
					system("cls");
					gridSearch();
					cout << endl;
					system("pause");
					break;
				}
			case 'M':
			case 'm':
				{
				system("cls");
				cout << "Enter the number to be mirrored" << endl << "\n\t";
// validate positive and whole
				if(!(cin >> num))
				{
					cout << "thats not a int, try again.";
					thechoice = '#';

								// {// flush cin buffer somehow...}

					system("pause");
					break;
				}
				NumReverse(num);
				break;
				}
			case 'G':
			case 'g':
				{
					system("cls");
					unsigned int num1,num2;
					cout << "Enter two intigers to find their GCD"<<endl;
					cin >> num1 >>num2;
					cout << GCD(num1,num2) << endl;
					system("pause");
					break;
				}
			case 'Q':
			case 'q':
				{
					thechoice  = '!';
					break;
				}
			default:
				{
					cout << "Enter S, M, G, or Q followed by the enter key.\n\n";
					cin.clear();

					system("pause");
					break;
				}
		}}

		cout << "\n\tend Of prog\n";
		system("pause");
	return 0;
}

///////////////////////////////////////////////////////////////////////////////////////// FXN METHODS
bool posWhole(int checkme)
{
	return true;
}

void NumReverse(int reverseme)
{
	if(reverseme<=0)
	{	cout << "Bad Input";
		system("pause");
		return;
	}
	else{
		//base case: 1 digit.
		if((reverseme/10) < 1)
		{
			cout << reverseme << "...is the mirrored number." << endl;
			system("pause");
			system("cls");
			return ;
		}
		//recursive step:
		cout << (reverseme%10);
		NumReverse(reverseme/10);
	}
}

void setOrder(int num1, int num2)
{
	if(num1>num2)
	{
		int tempswap = num1;
		num1 = num2;
		num2 = tempswap;
	}
}

int GCD(int num1, int num2)
{
	setOrder(num1,num2);
	while(num1<=0 || num2<=0)
	{
		cout << "No negative numbers"<<endl;
		cin >> num1 >> num2;
	}
	if(num1%num2 ==0)
	{
		return num2;
	}
	return (GCD(num2,(num1%num2)));
}

void gridSearch()
{
	int findme=0;
		ifstream in;
	in.open("values.txt");
	if(!in)	//crap on invalid input
	{
		cout << "Wrong file, Ya Hippy\n";
		system("pause");
		return;
	}

	int i,tmp,gridctr = 0;
	cout<<"\n   ";
			for(i=0;i<TABLE_COLS;i++)//print top row

			{
				cout <<setw(4)<< i;
			}
			cout << endl;
	while(!in.eof()) // File reading begins here
	{
		for(i=0;i<TABLE_ROWS;i++)// FOR EACH ROW
		{
			for(int j=0;j<TABLE_COLS;j++) //FILL ITS COL VALUES
			{
				//char tmp;
				if(j==0) //insert a left margin
					cout<<endl<<setw(3)<<i;
				in >> tmp;
				cout << setw(4)<< tmp; 

				//grid[TABLE_ROWS][TABLE_COLS] = tmp;    //write tmp to array   

				//the above doest nothing at all????!!! Driving me friggin crazy!!!!
				//I cant even attempt to search the grid without properly loading it.
				// im punking out and using a regular array
				grid[gridctr] = tmp;
				gridctr++;
			}
		}
	}
	// failed recursion attempt

	//int low = 0;
	//int high = 599;
	//cout << "\nEnter a number to Locate";
	//cin >> findme;
	//if(findme == grid[(high-low)/2])
	//{
	//	cout << "\nnumber found at row:" << (i%20) << "  col:" << (grid[(high-low)/2]%20);
	//}
	//else{
	//	if(findme < grid[(high-low)/2])
	//	{
	//		return;                            //cant figure out how to modularize and still be able to lookup the grid
	//	}
	//}

	//iterative punkout... gotta turn in something that runs..

	while(findme>=0)
	{
		cout << "\nEnter a number to Locate. Any negative entry will exit";
		cin >> findme;
		i=0;
		while(grid[i] <= findme)
		{
			if(grid[i]==findme)
				cout << "\nnumber found at row:" << (i/20) << "  col:" << (i%20);
			i++;
		}
	}findme=0;
}

Dynamic Array Example C++

//this is an example of an array of dynamic memory

#include <iostream>
using namespace std;
void main()
{
   typedef int* IntPtr;
   IntPtr intList;
   int listSize;
   cout << "How big is the list? ";
   cin >> listSize;
   intList = new int[listSize];
   for (int i = 0; i < listSize; i++)
   {
      intList[i] = i;
      cout << intList[i] << ' ' << &intList[i] << endl;
   }
   cout << endl;
   delete [] intList; //ALLWAYS remember to match new statements with delete statements
   system("pause");
}

A realistic C++ line counter

This program asks the user for a c++ source file. It displays the file’s linecount to the screen. Program exits on invalid input. This sourcefile is 90 lines of code(according to itself).
Each of the following counts as one line of code:

  1. Preprocessor directives
  2. if()
  3. while()
  4. do..while()
  5. switch()
  6. non-repeating semicolons

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

// accepts a valid C++ filename, returns a C++ linecount. Prints a error and exits program on invalid input.
int loc(string filename);

int main()
{
	string filename;
	cout << "Enter a cpp filename to linecount " << endl;
	cin >> filename;
	cout << filename << " has " << loc(filename) << " lines of code." << endl;
	system("pause");
	return 0;
}

int loc(string filename){
/* open file. exit on failure
 * read the file one character at a time
 * accumulate a linecount by counting if, do, while, switch and semicolons.
 * ignore keywords and semi's that are inside strings and comments
 */
    ifstream OpenFile;
    OpenFile.open(filename.c_str());
    char ch;
    int linecount = 0;

    if (!OpenFile) {
    cout << "loc() was unable to open file. Exiting program." << endl;
	system("pause");
	exit(1);
    }

    while(!OpenFile.eof()){

        OpenFile.get(ch);

        //dont count anything inside line or block comments
        if(ch == '/'){
                OpenFile.get(ch);
                if(ch == '/'){
                        while(ch != '\n')
                                OpenFile.get(ch);
                }else if(ch == '*'){
                        OpenFile.get(ch);
                        while(ch != '*' && ch+1 != '/'){
                                OpenFile.get(ch);
                        }
                }

        // handle the \" escape character here, to prevent errors in string parsing
        }else if(ch == '\\'){
            if(OpenFile.peek()=='\"'){
                OpenFile.get(ch);
                OpenFile.get(ch);
            }

        // dont count anything inside of strings, remember to ignore the /" escape character
        }else if(ch=='\"'){
            OpenFile.get(ch);
            while(ch!='\"'){
                if(ch == '\\'){
                    if(OpenFile.peek()=='\"'){
                        OpenFile.get(ch);
                        OpenFile.get(ch);
                    }
                }OpenFile.get(ch);
            }
        }

        // count if()'s
        else if(ch == 'i'){
                if(OpenFile.peek() == 'f'){
                        OpenFile.get(ch);
                        if(OpenFile.peek() == ' ' || OpenFile.peek() == '('  || OpenFile.peek() == '\n' || OpenFile.peek() == '\r' || OpenFile.peek() == '\t' ){
                                linecount++;
                        }
                }
        }

        // count while()'s
        else if(ch == 'w'){
                if(OpenFile.peek() == 'h'){
                        OpenFile.get(ch);
                        if(OpenFile.peek() == 'i'){
                                OpenFile.get(ch);
                                if(OpenFile.peek() == 'l'){
                                OpenFile.get(ch);
                                        if(OpenFile.peek() == 'e'){
                                        OpenFile.get(ch);
                                                if(OpenFile.peek() == ' ' || OpenFile.peek() == '('  || OpenFile.peek() == '\n' || OpenFile.peek() == '\r' || OpenFile.peek() == '\t' ){
                                                linecount++;
                                                }
                                        }
                                }
                        }
                }

        // count do..while();    this routine eliminates double counting because do{..}while(); loops always end with a semi.
                // the whole block is effectivly ignored, and the ending semi is counted like normal
        }else if(ch == 'd'){
                if(OpenFile.peek() == 'o'){
                        OpenFile.get(ch);
                        bool flag = false;
                        while( !flag ){
                                OpenFile.get(ch);
                                if(ch == 'w'){
                                        if(OpenFile.peek() == 'h'){
                                                OpenFile.get(ch);
                                                if(OpenFile.peek() == 'i'){
                                                        OpenFile.get(ch);
                                                        if(OpenFile.peek() == 'l'){
                                                        OpenFile.get(ch);
                                                                if(OpenFile.peek() == 'e'){
                                                                OpenFile.get(ch);
                                                                        if(OpenFile.peek() == ' ' || OpenFile.peek() == '('  || OpenFile.peek() == '\n' || OpenFile.peek() == '\r' || OpenFile.peek() == '\t' ){
                                                                        flag = true;
                                                                        }
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                }
        }

        // count switch()'s
        else if(ch == 's'){
                if(OpenFile.peek() == 'w'){
                        OpenFile.get(ch);
                        if(OpenFile.peek() == 'i'){
                                OpenFile.get(ch);
                                if(OpenFile.peek() == 't'){
                                OpenFile.get(ch);
                                        if(OpenFile.peek() == 'c'){
                                        OpenFile.get(ch);
                                                if(OpenFile.peek() == 'h'){
                                                OpenFile.get(ch);
                                                        if(OpenFile.peek() == ' ' || OpenFile.peek() == '('  || OpenFile.peek() == '\n' || OpenFile.peek() == '\r' || OpenFile.peek() == '\t' ){
                                                        linecount++;
                                                        }
                                                }
                                        }
                                }
                        }
                }
        }

        // counts semi's, remember that ;;;;; only counts as one line, not 5.
        else if(ch == ';'){
                while ( OpenFile.peek() == ';' || OpenFile.peek() == ' '  || OpenFile.peek() == '\n' || OpenFile.peek() == '\r' || OpenFile.peek() == '\t' ){
                        OpenFile.get(ch);
                }
                linecount++;
        }

        //and count meta, # character counting is all thats necessasary because
        else if(ch == '#'){
                linecount++;
        }
    }

    OpenFile.close();
    return linecount;
}

16 bit ALU Verilog design

//B Turley
//16 bit ALU

`timescale 1ns/100ps

module sep_alu(Y, cout16, cout15, rightout, leftout, A, B, s, cin, rightin, leftin);
    output [15:0] Y;
    output cout16, cout15;
    output rightout, leftout;
    input  [15:0] A; //first input
    input  [15:0] B; //second input
    input  [3:0]  s; //operation input
    input         cin; // carry in
    input rightin, leftin; // shift inputs

    wire    [15:0]  cvect;
    wire    [15:0]  rvect;
    wire    [15:0]  lvect;

        alu_slice u0(Y[0], cvect[0], rvect[0], lvect[0],  A[0], B[0], s, cin, rvect[1], leftin);
        alu_slice u1(Y[1], cvect[1], rvect[1], lvect[1],  A[1], B[1], s, cvect[0], rvect[2], lvect[0]);
        alu_slice u2(Y[2], cvect[2], rvect[2], lvect[2],  A[2], B[2], s, cvect[1], rvect[3], lvect[1]);
        alu_slice u3(Y[3], cvect[3], rvect[3], lvect[3],  A[3], B[3], s, cvect[2], rvect[4], lvect[2]);
        alu_slice u4(Y[4], cvect[4], rvect[4], lvect[4],  A[4], B[4], s, cvect[3], rvect[5], lvect[3]);
        alu_slice u5(Y[5], cvect[5], rvect[5], lvect[5],  A[5], B[5], s, cvect[4], rvect[6], lvect[4]);
        alu_slice u6(Y[6], cvect[6], rvect[6], lvect[6],  A[6], B[6], s, cvect[5], rvect[7], lvect[5]);
        alu_slice u7(Y[7], cvect[7], rvect[7], lvect[7],  A[7], B[7], s, cvect[6], rvect[8], lvect[6]);
        alu_slice u8(Y[8], cvect[8], rvect[8], lvect[8],  A[8], B[8], s, cvect[7], rvect[9], lvect[7]);
        alu_slice u9(Y[9], cvect[9], rvect[9], lvect[9],  A[9], B[9], s, cvect[8], rvect[10], lvect[8]);
        alu_slice u10(Y[10], cvect[10], rvect[10], lvect[10],  A[10], B[10], s, cvect[9], rvect[11], lvect[9]);
        alu_slice u11(Y[11], cvect[11], rvect[11], lvect[11],  A[11], B[11], s, cvect[10], rvect[12], lvect[10]);
        alu_slice u12(Y[12], cvect[12], rvect[12], lvect[12],  A[12], B[12], s, cvect[11], rvect[13], lvect[11]);
        alu_slice u13(Y[13], cvect[13], rvect[13], lvect[13],  A[13], B[13], s, cvect[12], rvect[14], lvect[12]);
        alu_slice u14(Y[14], cvect[14], rvect[14], lvect[14],  A[14], B[14], s, cvect[13], rvect[15], lvect[13]);
        alu_slice u15(Y[15], cvect[15], rvect[15], lvect[15],  A[15], B[15], s, cvect[14], rightin, lvect[14]);

        assign cout16 = cvect[15];
        assign cout15 = cvect[14];
        assign rightout = rvect[0];
        assign leftout = lvect[15];

endmodule
/*****************************************************

File: sep_alu_tb.v
Author: Jeremy Wood
Date: 6-8-04

Desc: This is the test bench for the ALU 

modified 9-18-04  Added driveable left and right
                  shift inputs
modified 2-17-11  By B K Turley,
					Corrected error with cin timing
*****************************************************/

`timescale 1ns/100ps

module sep_alu_tb;

        reg     [15:0]  A;                      // A Input
        reg     [15:0]  B;                      // B Input
        reg     [3:0]   s;                      // Operation select input
        reg             cin;                    // Carry input
        reg             rightIn;                // Right Input from the shift operations
        reg             leftIn;                 // Left Input from the shift operations

        wire    [15:0]  Y;                      // Y Ouput
        wire            cout16, cout15;          // Carry Outputs
        wire            rightout, leftout;       // Shift Outputs

        // Invoke an instance of the test bench
        sep_alu         alu(Y, cout16, cout15, rightout, leftout, A, B, s, cin, rightIn, leftIn);

        initial begin

                $dumpfile("./sep_alu.dmp");
                $dumpvars(6, sep_alu_tb);

                A <= 16'habcd;
                B <= 16'h1234;
                rightIn <= 1'b0;
                leftIn <= 1'b0;

                // Addition
                #20 s <= 4'b0000;
                cin <= 1'b0;

                // Addition with Carry
                #20 cin <= 1'b1;

                // Subtract with Borrow
                #20 s <= 4'b0001;
                cin <= 1'b0;

                // Subtraction
                #20 cin <= 1'b1;

                // Transfer A
                #20 s <= 4'b0010;
                cin <= 1'b0;

                // Increment
                #20 cin <=1'b1;

                // Decrement A
                #20 s <= 4'b0011;
                cin <= 1'b0;

                // Transfer A
                #20 s <= 4'b0010;

                // AND
                #20 s <= 4'b0100;

                // OR
                #20 s <= 4'b0101;

                // XOR
                #20 s <= 4'b0110;

                // Complement A
                #20 s <= 4'b0111;

                // Shift right A into F
                #20 s <= 4'b1000;

                // Shift left A into F
                #20 s <= 4'b1100;

                // 42 + -13
                #20 A <= 16'd42;
                    B <= 16'b1111111111110011;
                    s <= 4'd0;

                // -42 - -13
                #20 A <= 16'b1111111111010110;
                    B <= 16'b1111111111110011;
                    s <= 4'd1;

                // 70 + 80
                #20 A <= 16'd70;
                    B <= 16'd80;
                    s <= 4'd0;

                // -70 + -80
                #20 A <= 16'b1111111110111010;
                    B <= 16'b1111111110110000;

                // Clear signals for Simvision
                #20 A <= 16'h0000;
                    B <= 16'h0000;

                #20 $finish;
        end
endmodule
//B Turley
//ALU one bit slice

`timescale 1ns/100ps

module alu_slice(Y, cout, rightout, leftout, A, B, s, cin, rightin, leftin);
    output Y;
    output cout;
    output rightout, leftout;
    input A;
    input B;
    input [3:0] s;
    input cin;
    input rightin, leftin;

    wire sum;
    wire Bin, Lout;

    mux_4to1 arithmatic(Bin, s[1:0], B, ~B, 1'b0, 1'b1);
    mux_4to1 logicpart(Lout, s[1:0], A&B, A|B, A^B, ~A);
    adder_1bit adder(sum, cout, A, Bin, cin);
    mux_4to1 slicemux(Y, s[3:2], sum, Lout, rightin, leftin);

    assign rightout = A;
    assign leftout = A;

endmodule
// 1 bit adder
// BK Turley

`timescale 1ns/100ps

module adder_1bit(sum, cout, in1, in2, cin);

        input   in1;
        input   in2;
        input   cin;

        output  sum;
        output  cout;

        assign cout = (in1 & in2) | (in1 & cin) | (in2 & cin);
        assign sum = in1 ^ in2 ^ cin;

endmodule

// 4 channel, 1 bit mux
// BK Turley

`timescale 1ns/100ps

module mux_4to1(out, sel, in0, in1, in2, in3);

output out;
input [1:0] sel;
input in0;
input in1;
input in2;
input in3;

reg out;

always @( sel or in0 or in1 or in2 or in3)

case (sel)
2′b00 : out <= in0;
2′b01 : out <= in1;
2′b10 : out <= in2;
2′b11 : out <= in3;
default : out <= in0;
endcase

endmodule

8 channel, 16 bit Verilog Multiplexer

// 8 channel mux
// BK Turley

`timescale 1ns/100ps

module mux_8to1_16bit(out, sel, in0, in1, in2, in3, in4, in5, in6, in7);

	input	[2:0]	sel;
	input	[15:0]	in0;
	input	[15:0]	in1;
	input	[15:0]	in3;
	input	[15:0]	in4;
	input	[15:0]	in5;
	input	[15:0]	in6;
	input	[15:0]	in7;
	output	[15:0]	out; 

	reg	[15:0]	out; 

	always @( sel or in0 or in1 or in2 or in3
		      or in4 or in5 or in6 or in7)

		case (sel)
		    3'b000 :	out <= in0;
		    3'b001 :	out <= in1;
		    3'b010 :	out <= in2;
		    3'b011 :	out <= in3;
		    3'b100 :	out <= in4;
		    3'b101 :	out <= in5;
		    3'b110 :	out <= in6;
		    3'b111 :	out <= in7;
		    default :	out <= in0; // channel 0 is selected on high impedence input
		endcase

endmodule

// B. Turley
//mux_8to1_16bit_tb.v

`timescale 1ns/100ps

module mux_8to1_16bit_tb;

    reg     [2:0]   mux_sel;
	reg     [15:0]  mux_in0;
	reg     [15:0]  mux_in1;
	reg     [15:0]  mux_in2;
	reg     [15:0]  mux_in3;
	reg     [15:0]  mux_in4;
	reg     [15:0]  mux_in5;
	reg     [15:0]  mux_in6;
	reg     [15:0]  mux_in7;
	wire    [15:0]  mux_out;

	mux_8to1_16bit  mux(mux_out, mux_sel, mux_in0, mux_in1, mux_in2,
		mux_in3, mux_in4, mux_in5, mux_in6, mux_in7);

	initial begin

		$dumpfile("./mux_8to1_16bit.dmp");
		$dumpvars(2, mux_8to1_16bit_tb);

		mux_in0 <= 16'h0000;
		mux_in1 <= 16'h0001;
		mux_in2 <= 16'h0002;
		mux_in3 <= 16'h0003;
		mux_in4 <= 16'h0004;
		mux_in5 <= 16'h0005;
		mux_in6 <= 16'h0006;
		mux_in7 <= 16'h0007;
		mux_sel <= 3'b000;

		#20 mux_sel <= 3'b001;
		#20 mux_sel <= 3'b010;
		#20 mux_sel <= 3'b011;
		#20 mux_sel <= 3'b100;
		#20 mux_sel <= 3'b101;
		#20 mux_sel <= 3'b110;
		#20 mux_sel <= 3'b111;
		#20 mux_sel <= 3'b000;

		#20 $finish;
	end
endmodule

Verilog 16 bit register with testbench.

//16 bit Register by B Kyle Turley
//Verilog

`timescale 1ns/100ps

module reg_16bit (out, in, load, clear, clk);
 input   [15:0]   in;
 input           load;
 input           clear;
 input           clk;
 output  [15:0]   out;

 reg     [15:0]   Q;

 always @(posedge clk)
 begin
 if(clear == 1'b1) // If clear is high, it has priority
 Q <= 16'b000000000000000;
 else if(load == 1'b1) // load has the next highest
 Q <= in;
 else
 Q <= Q;
 end

 /* Set output equal to the internal state */
 assign out = Q;

endmodule
`timescale 1ns/100ps

module reg_16bit_tb;

	reg	[15:0]	reg_input;
	reg		reg_load;
	reg		reg_clear;
	reg		clk;

	wire	[15:0]	reg_out;
	integer		fid;

	reg_16bit	register(reg_out, reg_input, reg_load, reg_clear, clk);

	initial begin
		clk = 1'b0;
		forever #10 clk <= ~clk;
	end

	initial begin

		fid = $fopen("./reg_16bit.out");
		$fmonitor(fid, $time, " out = %h, in = %h, load = %b, clear = %b",
			reg_out, reg_input, reg_load, reg_clear ) ;

		$dumpfile("./reg_16bit.dmp");
		$dumpvars(2, reg_16bit_tb);

		reg_clear <= 1'b1;
		reg_load <= 1'b0;
		reg_input <= 16'hABCD;
		#20 reg_clear <= 1'b0;
		#20 reg_load <= 1'b1;
		#20 reg_load <= 1'b0;
		#20 reg_input <= 16'h1234;
		#20 reg_load <= 1'b1;
		#20 reg_load <= 1'b0;
		reg_input <= 16'h0000;
		reg_clear <= 1'b1;
		#20 reg_clear <= 1'b0;
		#20 $finish;
	end

endmodule

Can’t use a string in a switch statement? Here is a simple alternative

Many programmers are surprised to find that switch statements aren’t compatible with strings in C++.

When attempting to compile, you will see an error:

Visual Studio 2010 —–  error C2450: switch expression of type ‘std::string’ is illegal

Netbeans 6.9.1 —– error: switch quantity not an integer

Here is an example of invalid code

#include <iostream>
#include <string>

using namespace std;

int main(){

	string dayofweek = "wednesday";

	switch(dayofweek){
		case "monday":
			cout << "Watch football" << endl;
			break;
		case "tuesday":
			cout << "steal a car"<< endl;
			break;
		case "wednesday":
			cout << "rob a bank" << endl;
			break;
		case "thursday":
			cout << "count the money" << endl;
			break;
		case "friday":
			cout << "hire a good lawyer" << endl;
			break;
	}
	return 0;
}

The problem is that strings are not a basic type in the C++ language. Whenever a C++ programmer uses basic variables types like int, bool, and char, nothing extra needed. But when a C++ programmer wishes to use strings in a program, they must add #include <string> to the top of the code to enable that functionality. Basic switch statements don’t have the capability to understand “add on” features such as strings and other filestreams.

There is still hope. The people who created the string library were kind enough to include a function to compare strings – strcmp() function. The string compare function can be used along with if..else statements to achieve the desired result.

this is the same logic as before without using a switch statement:

#include <iostream>
#include <string>

using namespace std;

int main(){

	string str = "wednesday";

	if ((!strcmp(str.c_str(), "monday"))){
		cout << "Watch football" << endl;
	}else if (!strcmp(str.c_str(), "tuesday")){
        cout << "steal a car"<< endl;
	}else if (!strcmp(str.c_str(), "wednesday")){
        cout << "rob a bank" << endl;
	}else if (!strcmp(str.c_str(), "thursday")){
		cout << "count the money" << endl;
	}else if (!strcmp(str.c_str(), "friday")){
		cout << "hire a good lawyer" << endl;
	}else{ // same as default
		cout << "Enjoy the Weekend" << endl;
	}

	return 0;
}