Project 1 || Wong Edition || C++ Project || B.Tech Diaries

Project #1 - Sorted Date List

  • Read a sequence of dates from file input.
  • Permissible formats for dates include
    dd/mm/yyyy e.g. 01/01/1970
    
    d MMM yyyy e.g. 1 JAN 1970
    
    MMM d, 1970 e.g. JAN 1, 1970
    
    MMMM d, yyyy e.g. January 1, 1970.
    
  • Sort and output the dates such that the later dates come first.
  • Use functions from the STL's: `<string>`, `<algorithm>`, `<regex>`, `<iterator>`, `<array>`.
  • Create your customised MyDate class.

Solution:


#include <iostream>
#include <string>
#include <algorithm>
#include <regex>
#include <iterator>
#include <array>
#include <fstream>
#include <iomanip>

#define N 25

class Date
{
private:
    int day;
    int month;
    int year;
    std::array<std::string, 12> _months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

public:
    Date()
    {
        day = 9999;
        month = 9999;
        year = 9999;
    }
    Date(std::string str_date)
    {
        day = 1;
        month = 1;
        year = 1970;
        _date_parser(str_date);
    }
    ~Date() {}
    bool is_valid()
    {
        if (day > 31 || day < 1)
            return false;
        if (month > 12 || month < 1)
            return false;
        if (year > 9999 || year < 1000)
            return false;
        return true;
    }
    void _date_parser(std::string str_date)
    {
        std::string _months_abbr_pattern = "", _months_pattern = "";
        for (size_t i = 0; i < _months.size(); i++)
        {
            _months_abbr_pattern += _months[i].substr(0, 3);
            if (_months.size() - 1 != i)
            {
                _months_abbr_pattern += "|";
            }
        }
        for (size_t i = 0; i < _months.size(); i++)
        {
            _months_pattern += _months[i];
            if (_months.size() - 1 != i)
            {
                _months_pattern += "|";
            }
        }

        std::array<std::regex, 10> patterns({
            std::regex("([0-2][1-9]|3[0-1])\\s*[, /\\-]\\s*(0[1-9]|1[0-2])\\s*[, /\\-]\\s*([1-5]\\d{3})"),
            std::regex("([1-9]|[1-2][1-9]|3[0-1])\\s*[, /\\-]\\s*(" + _months_abbr_pattern + ")\\s*[, /\\-]\\s*([1-5]\\d{3})", std::regex::icase),
            std::regex("(" + _months_abbr_pattern + ")\\s*[, /\\-]\\s*([1-9]|[1-2][1-9]|3[0-1])\\s*[, /\\-]\\s*([1-5]\\d{3})", std::regex::icase),
            std::regex("(" + _months_pattern + ")\\s*[, /\\-]\\s*([1-9]|[1-2][1-9]|3[0-1])\\s*[, /\\-]\\s*([1-5]\\d{3})", std::regex::icase),
        });

        std::smatch match;
        bool check = false;
        for (size_t i = 0; i < patterns.size(); i++)
        {
            if (std::regex_match(str_date, patterns[i]))
            {
                std::regex_search(str_date, match, patterns[i]);
                switch (i)
                {
                case 0:
                    day = std::stoi(match[1].str());
                    month = std::stoi(match[2].str());
                    year = std::stoi(match[3]);
                    break;
                case 1:
                    day = std::stoi(match[1].str());
                    month = _months.size();
                    for (size_t i = 0; i < _months.size(); i++)
                    {
                        if (_months[i].substr(0, 3) == match[2].str())
                        {
                            month = i + 1;
                            break;
                        }
                    }
                    year = std::stoi(match[3]);
                    break;
                case 2:
                    day = std::stoi(match[2].str());
                    month = _months.size();
                    for (size_t i = 0; i < _months.size(); i++)
                    {
                        if (_months[i].substr(0, 3) == match[1].str())
                        {
                            month = i + 1;
                            break;
                        }
                    }
                    year = std::stoi(match[3]);
                    break;
                case 3:
                    day = std::stoi(match[2].str());
                    month = _months.size();
                    for (size_t i = 0; i < _months.size(); i++)
                    {
                        if (_months[i] == match[1].str())
                        {
                            month = i + 1;
                            break;
                        }
                    }
                    year = std::stoi(match[3]);
                    break;
                }
                check = true;
                break;
            }
        }
        if (!check)
            std::cout << "Invalid Format" << std::endl;
    }

    bool operator>(Date d)
    {
        if (year > d.year)
            return true;
        else if (year == d.year)
        {
            if (month > d.month)
                return true;
            else if (month == d.month)
            {
                if (day > d.day)
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
        return false;
    }

    bool operator<(Date d)
    {
        if (year < d.year)
            return true;
        else if (year == d.year)
        {
            if (month < d.month)
                return true;
            else if (month == d.month)
            {
                if (day < d.day)
                    return true;
                else
                    return false;
            }
            else
                return false;
        }
        return false;
    }

    std::string _str()
    {
        std::string str_date = "";
        str_date += std::to_string(day) + " ";
        str_date += _months[month - 1] + " ";
        str_date += std::to_string(year);
        return str_date;
    }

    friend std::ostream &operator<<(std::ostream &os, Date &date)
    {
        os << date._str();
        return os;
    }
};

std::array<Date, N> get_dates(std::string filename)
{
    std::ifstream infile;
    std::string str_date;

    std::array<Date, N> date_array;
    std::cout << "Get Dates from " << filename << " ... " << std::endl;
    int i = 0;
    infile.open(filename);
    while (std::getline(infile, str_date))
    {
        if (str_date != "")
            date_array[i++] = Date(str_date);
    }
    infile.close();

    return date_array;
}

int main(int argc, char const *argv[])
{
    std::array<Date, N> dates = get_dates("date_list.txt");

    std::cout << "Sorting Dates ... " << std::endl;
    std::sort(dates.begin(), dates.end());

    std::array<Date, N>::iterator it;
    for (it = dates.begin(); it != dates.end(); it++)
    {
        if (it->is_valid())
            std::cout << *it << std::endl;
    }

    return 0;
}

Input (date_list.txt):


30/01/3055
30-02-4849
30 01, 3459
16/11/5509
30-06/1571
13-Aug-1768
30/ Apr/1002
2 May 2668
29 JAN, 5802
31 Jul 2224
Jan 7 3106
Apr 31 1632
Mar 6 ,3214
Feb 19, 5063
Sep 6-3652
April 30, 5889
January 13 ,4035
May 21 2671
June 30, 4785
JANUARY 4 2324

Output:


Get Dates from date_list.txt ... 
Sorting Dates ...
30 April 1002
30 June 1571
31 April 1632
13 August 1768
31 July 2224
4 December 2324
2 May 2668
21 May 2671
30 January 3055
7 January 3106
6 March 3214
30 January 3459
6 September 3652
13 January 4035
30 June 4785
30 February 4849
19 February 5063
16 November 5509
29 December 5802
30 April 5889

Share:

Programming with C++ - Day8 || Wong Edition || B.Tech Diaries

Lab #8 - Standard Template Library (STL)

Resources

Question 1 - Acrobatics with Strings

Write a program that creates 2 strings then prints out the letters they have in common.

Solution:


#include <bits/stdc++.h>

// Question 1
void commonLetters(std::string s1, std::string s2)
{
    std::string s = "";
    auto it = std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(s));
    std::cout << s << std::endl;
}

int main(int argc, char const *argv[])
{
    std::string s1 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Nec feugiat in fermentum posuere urna. Nunc sed blandit libero volutpat sed cras ornare. Commodo quis imperdiet massa tincidunt nunc pulvinar sapien et ligula. A scelerisque purus semper eget. Pellentesque elit ullamcorper dignissim cras tincidunt lobortis. Mattis aliquam faucibus purus in massa tempor nec feugiat nisl. Tortor id aliquet lectus proin. Nulla posuere sollicitudin aliquam ultrices sagittis. Sed adipiscing diam donec adipiscing. Bibendum enim facilisis gravida neque convallis a cras.",
                s2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Sit amet nisl suscipit adipiscing bibendum. Sed viverra ipsum nunc aliquet bibendum enim facilisis gravida. Ipsum suspendisse ultrices gravida dictum fusce ut placerat orci nulla. Et magnis dis parturient montes. Blandit massa enim nec dui nunc mattis enim ut tellus. Tempus quam pellentesque nec nam aliquam. Aenean pharetra magna ac placerat vestibulum lectus mauris ultrices eros. Tristique nulla aliquet enim tortor at auctor urna nunc id. In fermentum et sollicitudin ac orci phasellus. Senectus et netus et malesuada fames ac.";
    commonLetters(s1, s2);
    return 0;
}

Output:


Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ut iumvvrsuuuussrvidauv

Question 2 - Sorting Vehicles

Create instances of the Vehicle class (from Lab #7) e.g. 3 BUSes, 4 CARs, 2 AUTOs, 5 SCOOTERs.

Store them in a Vector and sort them according to size.

Solution:


#include <bits/stdc++.h>

// Question 2
class Vehicle
{
private:
    std::string name;
    int legs;
    double cost;

public:
    Vehicle()
    {
    }
    Vehicle(std::string n, int l, double c)
    {
        legs = l;
        cost = c;
        name = n;
    }
    ~Vehicle()
    {
    }

    double _cost()
    {
        return cost;
    }

    bool operator>(Vehicle v)
    {
        return (legs > v.legs) || (legs == v.legs && cost > v.cost);
    }
    bool operator<(Vehicle v)
    {
        return (legs < v.legs) || (legs == v.legs && cost < v.cost);
    }

    bool operator==(Vehicle v)
    {
        return (legs == v.legs) && (cost == v.cost);
    }

    std::string to_string()
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    operator std::string() const
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    friend std::ostream &operator<<(std::ostream &out, Vehicle &v)
    {
        out << v.to_string();
        return out;
    }
};

void sortVehicles(std::vector<Vehicle> &vehicles)
{
    struct
    {
        bool operator()(Vehicle v1, Vehicle v2)
        {
            return v1._cost() > v2._cost();
        }
    } smallerSize;

    std::sort(vehicles.begin(), vehicles.end(), smallerSize);
    // return vehicles;
}

int main(int argc, char const *argv[])
{
    std::vector<Vehicle> vehicles;
    vehicles.push_back(Vehicle("car", 4, 100));
    vehicles.push_back(Vehicle("car", 4, 200));
    vehicles.push_back(Vehicle("car", 4, 300));
    vehicles.push_back(Vehicle("car", 4, 400));
    vehicles.push_back(Vehicle("bus", 4, 400));
    vehicles.push_back(Vehicle("bus", 4, 300));
    vehicles.push_back(Vehicle("bus", 4, 200));
    vehicles.push_back(Vehicle("auto", 3, 400));
    vehicles.push_back(Vehicle("auto", 3, 300));
    vehicles.push_back(Vehicle("scooter", 2, 50));
    vehicles.push_back(Vehicle("scooter", 2, 100));
    vehicles.push_back(Vehicle("scooter", 2, 120));
    vehicles.push_back(Vehicle("scooter", 2, 150));
    vehicles.push_back(Vehicle("scooter", 2, 200));
    sortVehicles(vehicles);
    for (Vehicle v : vehicles)
    {
        std::cout << v << std::endl;
    }
    return 0;
}

Output:


car(4,400.000000)
bus(4,400.000000)
auto(3,400.000000)
car(4,300.000000)
bus(4,300.000000)
auto(3,300.000000)
car(4,200.000000)
bus(4,200.000000)
scooter(2,200.000000)
scooter(2,150.000000)
scooter(2,120.000000)
car(4,100.000000)
scooter(2,100.000000)
scooter(2,50.000000)

Question 3 - Rectangles and Squares

Using the Rectangle class from Lab #3, create a Square class.

Store instances of Rectangle and Square in a single Vector.

Sort them according to their area. [Hint: use Vector<Rectangle *>]

Solution:


    #include <bits/stdc++.h>

    // Question 3
    class Rectangle
    {
    private:
        int length, breadth;
        std::string colour;
    
    public:
        Rectangle();
        Rectangle(int, int, std::string);
        ~Rectangle();
        int getArea();
        std::string print();
        int compare(Rectangle);
        int _length();
        int _breadth();
        std::string _colour();
    };
    
    int Rectangle::_length()
    {
        return length;
    }
    
    int Rectangle::_breadth()
    {
        return breadth;
    }
    
    std::string Rectangle::_colour()
    {
        return colour;
    }
    
    Rectangle::Rectangle()
    {
        length = 0;
        breadth = 0;
        colour = "";
    }
    
    Rectangle::Rectangle(int length, int breadth, std::string colour)
    {
        this->length = length;
        this->breadth = breadth;
        this->colour = colour;
    }
    
    Rectangle::~Rectangle()
    {
    }
    
    int Rectangle::getArea()
    {
        return this->length * this->breadth;
    }
    
    std::string Rectangle::print()
    {
        std::stringstream ps;
        ps << "\nLength: " << this->length
           << "\nBreadth: " << this->breadth
           << "\nColour: " << this->colour
           << "\nArea: " << this->getArea() << std::endl;
        return ps.str();
    }
    
    int Rectangle::compare(Rectangle rect)
    {
        if (this->getArea() > rect.getArea())
            return 1;
        else if (this->getArea() < rect.getArea())
            return -1;
        return 0;
    }
    
    class Square : public Rectangle
    {
    
    private:
    public:
        Square();
        Square(int, std::string);
        ~Square();
        std::string print();
    };
    
    Square::Square()
    {
    }
    Square::Square(int side, std::string color) : Rectangle(side, side, color)
    {
    }
    
    Square::~Square()
    {
    }
    
    std::string Square::print()
    {
        std::stringstream ps;
        ps << "\nSide: " << this->_length()
           << "\nColour: " << this->_colour()
           << "\nArea: " << this->getArea() << std::endl;
        return ps.str();
    }
    
    int main(int argc, char const *argv[])
    {
        std::vector<Rectangle> rectangles;
        rectangles.push_back(Square(5, "S red"));
        rectangles.push_back(Square(10, "S blue"));
        rectangles.push_back(Square(15, "S green"));
    
        rectangles.push_back(Rectangle(5, 10, "R red"));
        rectangles.push_back(Rectangle(10, 15, "R blue"));
        rectangles.push_back(Rectangle(15, 20, "R green"));
    
        std::sort(rectangles.begin(), rectangles.end(), [](Rectangle a, Rectangle b)
                  { return a.compare(b) < 0; });
    
        for (Rectangle r : rectangles)
        {
            std::cout << r.print() << std::endl;
        }
    
        return 0;
    }      

Output:


    Length: 5
    Breadth: 5
    Colour: S red
    Area: 25
    
    
    Length: 5
    Breadth: 10
    Colour: R red
    Area: 50
    
    
    Length: 10
    Breadth: 10
    Colour: S blue
    Area: 100
    
    
    Length: 10
    Breadth: 15
    Colour: R blue
    Area: 150
    
    
    Length: 15
    Breadth: 15
    Colour: S green
    Area: 225
    
    
    Length: 15
    Breadth: 20
    Colour: R green
    Area: 300

Share:

Programming with C++ - Day7 || Wong Edition || B.Tech Diaries

Lab #7 - Templates

Question 1 - Function Template

The format for function declaration is:

template <class identifier> function_declaration;

The format for function call is:

function_name <type> (parameters);
  • Write a function template getLarger that takes two parameters of any (same) type and returns the larger of the two.
  • Write a class Vehicle and provide the implementation for the ">" operator. Use the Vehicle in the getLarger function from (a). E.g. Bus > Car > Auto > Scooter

Solution:


#include <iostream>

// question 1
class Vehicle
{
private:
    std::string name;
    int legs;
    double cost;

public:
    Vehicle()
    {
    }
    Vehicle(std::string n, int l, double c)
    {
        legs = l;
        cost = c;
        name = n;
    }
    ~Vehicle()
    {
    }
    bool operator>(Vehicle v)
    {
        return (legs > v.legs) || (legs == v.legs && cost > v.cost);
    }
    bool operator<(Vehicle v)
    {
        return (legs < v.legs) || (legs == v.legs && cost < v.cost);
    }

    bool operator==(Vehicle v)
    {
        return (legs == v.legs) && (cost == v.cost);
    }

    operator std::string() const
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    std::string to_string()
    {
        return name + "(" + std::to_string(legs) + "," + std::to_string(cost) + ")";
    }

    friend std::ostream &operator<<(std::ostream &out, const Vehicle &v);
};

template <typename T>
T getLarger(T a, T b)
{
    return (a > b) ? a : b;
}

template <typename T>
T getSmaller(T a, T b)
{
    return (a < b) ? a : b;
}

int main(int argc, char const *argv[])
{
    int N = 10;

    Vehicle vehicles[N];

    for (int i = 0; i < N; i++)
    {
        int legs = rand() % 4 + 2;
        double cost = rand() % 700 + 100;
        std::string name = "Vehicle " + std::to_string(i + 1);
        vehicles[i] = Vehicle(name, legs, cost);
    }

    std::cout << std::endl
                << "========Comparison of Vehicles========"
                << std::endl;

    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N - i - 1; j++)
        {
            Vehicle v1 = getLarger<Vehicle>(vehicles[j + 1], vehicles[j]);
            Vehicle v2 = getSmaller<Vehicle>(vehicles[j + 1], vehicles[j]);
            vehicles[j] = v1;
            vehicles[j + 1] = v2;
        }
    }

    for (int i = 0; i < N; i++)
    {
        std::cout << vehicles[i];
        if (i != N - 1)
            std::cout << " > ";
    }
    std::cout << std::endl
                << std::endl;

    return 0;
}


========Comparison of Vehicles========
Vehicle 1(5,286.000000) > Vehicle 8(5,226.000000) > Vehicle 4(4,592.000000) > Vehicle 7(4,559.000000) > Vehicle 6(4,427.000000) > Vehicle 3(3,635.000000) > Vehicle 5(3,621.000000) > Vehicle 2(3,315.000000) > Vehicle 9(2,626.000000) > Vehicle 10(2,536.000000)

Question 2 - Class Template

The format for function declaration is:

template <class identifier> class classname
  1. Write a class template MyArray that can store up to 10 elements of any type, with the following functions:-
    • addElement
    • sort
    • print
  2. Store Vehicle instances from Question 1 in MyArray and sort them.

Solution:


...
// question 2
template <typename T>
class MyArray
{
private:
    T *arr;
    int capacity, size;

public:
    MyArray()
    {
        capacity = 8;
        arr = new T[capacity];
        size = 0;
    }
    bool addElement(T item)
    {
        if (size == capacity)
        {
            T *temp = new T[capacity * 2];
            for (int i = 0; i < size; i++)
            {
                temp[i] = arr[i];
            }
            delete[] arr;
            arr = temp;
            capacity *= 2;
        }
        arr[size++] = item;
        return true;
    }
    void sort()
    {
        for (int i = 0; i < size; i++)
        {
            for (int j = i + 1; j < size; j++)
            {
                if (arr[j] > arr[i])
                {
                    std::swap(arr[i], arr[j]);
                }
            }
        }
    }
    T get(int index)
    {
        return arr[index];
    }
    T operator[](int index)
    {
        return arr[index];
    }
    std::string print()
    {
        std::string str = "[";
        for (int i = 0; i < size; i++)
        {
            str += arr[i].to_string();
            if (i != size - 1)
                str += ", ";
        }
        str += "]";
        return str;
    }
};

int main(int argc, char const *argv[])
{
    int N = 15;

    MyArray<Vehicle> vehicles;

    for (int i = 0; i < N; i++)
    {
        int legs = rand() % 4 + 2;
        double cost = rand() % 1000 * 0.1234 + 100;
        std::string name = "Vehicle " + std::to_string(i + 1);
        vehicles.addElement(Vehicle(name, legs, cost));
    }

    std::cout << "Vehicles before sorting" << std::endl;
    std::cout << vehicles.print()
              << std::endl
              << std::endl;

    std::cout << "Vehicles after sorting" << std::endl;

    vehicles.sort();

    return 0;
}


    Vehicles before sorting
[Vehicle 1(5,209.332400), Vehicle 2(3,212.911000), Vehicle 3(3,141.339000), Vehicle 4(4,160.712800), Vehicle 5(3,151.951400), Vehicle 6(4,103.331800), Vehicle 7(4,107.280600), Vehicle 8(5,214.268400), Vehicle 9(2,152.568400), Vehicle 10(2,190.822400), Vehicle 11(5,145.411200), Vehicle 12(5,152.938600), Vehicle 13(4,165.402000), Vehicle 14(4,115.178200), Vehicle 15(5,116.659000)]

Question 3 - Friend Function

In Question 1 and Question 2, the `printTypeString()` function in the Vehicle class was used to output Vehicle information.

Overload the cout "<<" operator to output Vehicle information. Declare the "<<" function as friend in the Vehicle class, so as to access Vehicle's private attributes:-

friend ostream& operator<<(ostream &out, const Vehicle& v)

Note: friend functions and classes should be used sparingly as they break the good idea of encapsulation.

Solution:


...
// question 3
std::ostream &operator<<(std::ostream &out, const Vehicle &v)
{
    out << v.operator std::string();
    return out;
}

int main(int argc, char const *argv[])
{
    int N = 15;

    MyArray<Vehicle> vehicles;

    for (int i = 0; i < N; i++)
    {
        int legs = rand() % 4 + 2;
        double cost = rand() % 1000 * 0.1234 + 100;
        std::string name = "Vehicle " + std::to_string(i + 1);
        vehicles.addElement(Vehicle(name, legs, cost));
    }

    std::cout << "Vehicles before sorting" << std::endl;
    std::cout << vehicles.print()
                << std::endl
                << std::endl;

    std::cout << "Vehicles after sorting" << std::endl;

    vehicles.sort();

    std::cout << vehicles.print() << std::endl;
    std::cout << std::endl;

    std::cout << vehicles[0] << std::endl;

    return 0;
}    

Output:


Vehicles before sorting
[Vehicle 1(5,209.332400), Vehicle 2(3,212.911000), Vehicle 3(3,141.339000), Vehicle 4(4,160.712800), Vehicle 5(3,151.951400), Vehicle 6(4,103.331800), Vehicle 7(4,107.280600), Vehicle 8(5,214.268400), Vehicle 9(2,152.568400), Vehicle 10(2,190.822400), Vehicle 11(5,145.411200), Vehicle 12(5,152.938600), Vehicle 13(4,165.402000), Vehicle 14(4,115.178200), Vehicle 15(5,116.659000)]

Vehicles after sorting
[Vehicle 8(5,214.268400), Vehicle 1(5,209.332400), Vehicle 12(5,152.938600), Vehicle 11(5,145.411200), Vehicle 15(5,116.659000), Vehicle 13(4,165.402000), Vehicle 4(4,160.712800), Vehicle 14(4,115.178200), Vehicle 7(4,107.280600), Vehicle 6(4,103.331800), Vehicle 2(3,212.911000), Vehicle 5(3,151.951400), Vehicle 3(3,141.339000), Vehicle 10(2,190.822400), Vehicle 9(2,152.568400)]

Vehicle 8(5,214.268400)

Share:

Programming with C++ - Day5 || Wong Edition || B.Tech Diaries

Lab #5 - Inheritance and Over-Riding

Question 1 - Company Hierarchy

In a Company Hierarchy consisting of Clerk, Manager and Director, the invoice approval limits are as follows:-

  • Clerk - $100
  • Manager - $500
  • Director - $1000

The UML Class Diagram for the Clerk is as shown.

Clerk
- name : String
- designation: String
* getName : String
* getDesignation : String
* introduce() : String
* approveInvoice(in invoiceAmount:double) : boolean
  • Depict the Company Hierarchy in a UML Class Diagram.
  • Implement the Company Hierarchy. Over-Ride the approveInvoice function to ensure the approval limits are adhered to. [Hint: create the main() loop in the Director class and create instances of Clerk, Manager and Director]

Solution:


#include <iostream>

/**
    * @brief Class Clerk
*/
class Clerk
{
private:
    std::string name, designation;

public:
    Clerk(std::string);
    Clerk(std::string, std::string);
    ~Clerk();
    std::string getName();
    std::string getDesignation();
    std::string introduce();
    bool approveInvoice(double);
};

Clerk::Clerk(std::string name)
{
    this->name = name;
    this->designation = "Clerk";
}

Clerk::Clerk(std::string name, std::string designation)
{
    this->name = name;
    this->designation = designation;
}

Clerk::~Clerk()
{
}

std::string Clerk::getName()
{
    return this->name;
}

std::string Clerk::getDesignation()
{
    return this->designation;
}

std::string Clerk::introduce()
{
    return "My name is " + this->name + " and I am a " + this->designation;
}

bool Clerk::approveInvoice(double amount)
{
    if (amount <= 100)
        return true;
    else
        return false;
}

/**
    * @brief Class Manager
*/

class Manager : public Clerk
{
private:
public:
    Manager(std::string);
    Manager(std::string, std::string);
    ~Manager();
    bool approveInvoice(double);
};

Manager::Manager(std::string name) : Clerk(name, "Manager")
{
}

Manager::Manager(std::string name, std::string designation) : Clerk(name, designation)
{
}

Manager::~Manager()
{
}

bool Manager::approveInvoice(double amount)
{
    if (amount <= 500)
        return true;
    else
        return false;
}

/**
    * @brief Class Manager
*/

class Director : public Manager
{
private:
public:
    Director(std::string);
    ~Director();
    bool approveInvoice(double);
};

Director::Director(std::string name) : Manager(name, "Director")
{
}

Director::~Director()
{
}

bool Director::approveInvoice(double amount)
{
    if (amount <= 1000)
        return true;
    else
        return false;
}

// program 1
int main(int argc, char const *argv[])
{
    Clerk clerk("John");
    Manager manager("Jane");
    Director director("Jack");

    std::cout << clerk.introduce() << std::endl;
    std::cout << manager.introduce() << std::endl;
    std::cout << director.introduce() << std::endl;

    std::cout << (clerk.approveInvoice(77) ? "True" : "False") << std::endl;
    std::cout << (clerk.approveInvoice(100) ? "True" : "False") << std::endl;
    std::cout << (clerk.approveInvoice(124) ? "True" : "False") << std::endl;

    std::cout << (manager.approveInvoice(427) ? "True" : "False") << std::endl;
    std::cout << (manager.approveInvoice(500) ? "True" : "False") << std::endl;
    std::cout << (manager.approveInvoice(584) ? "True" : "False") << std::endl;

    std::cout << (director.approveInvoice(927) ? "True" : "False") << std::endl;
    std::cout << (director.approveInvoice(1000) ? "True" : "False") << std::endl;
    std::cout << (director.approveInvoice(1084) ? "True" : "False") << std::endl;
    return 0;
}    

Output:


My name is John and I am a Clerk
My name is Jane and I am a Manager
My name is Jack and I am a Director
True
True
False
True
True
False
True
True
False

Question 2 - Company Hierarchy with Outsourcing

To cut costs, the Company decided to take on Contractors.

A Contractor has a Name in the company records, but has no formal designation. A Contractor cannot approveInvoice (but of course!).

Suppose that at a Company function, everyone has to introduce himself / herself:-

    Hello, my name is xxx.  My designation is XXX.
                          or
    Hello, my name is yyy.  I am a Contractor.
  • Design the new Company Hierarchy in a UML Class Diagram, to accommodate the Contractor. [Hint: pull up the common attributes / properties and behaviour into an Abstract Class.]
  • Implement the new Company Hierarchy. Keep the main() loop in the Director class.

Solution:


...
// program 2

class Contractor : protected Clerk
{
private:

public:
    Contractor(std::string);
    ~Contractor();
    std::string introduce();
    std::string getName();
};

Contractor::Contractor(std::string name) : Clerk(name)
{
}

Contractor::~Contractor()
{
}

std::string Contractor::introduce()
{
    return "My name is " + this->getName() + " and I am a Contractor";
}

std::string Contractor::getName()
{
    return Clerk::getName();
}

int main(int argc, char const *argv[])
{
    Contractor contractor("John");
    std::cout << contractor.introduce() << std::endl;
    std::cout << contractor.getName() << std::endl;

    return 0;
}


My name is John and I am a Contractor
John

Question 3 - Fraud!

Suppose a Director in the Company tries to impersonate his Clerk at the Company function by introducing himself as a Clerk. By using casting, show how that this is possible.


Clerk* cPtr = new Manager(...);
cPtr->introduce();   

Suppose a Clerk in the Company tries to impersonate his Manager at the Company function. Explain why this is not possible.


Manager* mPtr = new Clerk(...);
mPtr->introduce();

Solution:


...
// program 3
int main(int argc, char const *argv[])
{
    Clerk *cPtr = new Manager("John");
    std::cout << cPtr->introduce() << std::endl;

    try
    {
        Manager *mPtr = new Clerk("Jane");
        mPtr->introduce();
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << 'n';
    }

    return 0;
}


My name is John and I am a Manager

Share:

Programming with C++ - Day4 || Wong Edition || B.Tech Diaries

Lab #4 - Overloading

Question 1 - Employee

Create an Employee class according to the given Class Diagram.


Employee
- name: String
- gender: int
- colour : string
- Employee()
* Employee(in_name:String, in_gender:boolean)
- getName(): String
- getGender(): boolean
- print(): String

The default constructor is declared private to prevent its use. boolean getGender() returns FALSE if male and TRUE if female. The print() function gives the following sample output:

    Hello, my name is Arif. I am male.

From 2014, India officially recognises a third gender. Modify your design (i.e. give a new UML Class Diagram) to provide

    an overloaded constructor to take in gender information as an integer,
    an overloaded getGender() function that returns 0 if male, 1 if female and -1 if transgender, and
    an overloaded print() function that handles the third gender. 

In your main() loop, create

    2 Employee instances, hired before 2014, and
    3 Employee instances, hired after 2014.

Solution:


#include <iostream>
#include <sstream>

class Employee
{
private:
    std::string name;
    int gender;
    Employee();

public:
    Employee(std::string, bool);
    Employee(std::string, int);
    ~Employee();
    std::string getName();
    bool getGender();
    int getGender(int);
    std::string print();
    std::string print(int);
};

Employee::Employee()
{
}

Employee::~Employee()
{
}

Employee::Employee(std::string name, bool gender)
{
    this->name = name;
    this->gender = gender;
}

std::string Employee::getName()
{
    return name;
}

bool Employee::getGender()
{
    return gender;
}

std::string Employee::print()
{
    std::stringstream ps;
    ps << "Hello, my name is " << name << ". I am " << (gender == 0 ? "male" : "female") << "." << std::endl;
    return ps.str();
}

/*
    After 2014 changes
*/

Employee::Employee(std::string name, int gender)
{
    this->name = name;
    this->gender = gender;
}

int Employee::getGender(int i)
{
    if (i)
        return this->getGender();
    return gender;
}

std::string Employee::print(int i)
{
    if (i)
        this->print();

    std::stringstream ps;
    ps << "Hello, my name is " << name << ". I am " << (gender == 0 ? "male" : (gender == 1 ? "female" : "transgender")) << "." << std::endl;
    return ps.str();
}

int main(int argc, char const *argv[])
{
    Employee e1("Alpha", false), e2("Beta", true);
    std::cout << e1.print(0);
    std::cout << e2.print(0);
    Employee em1("Delta", 1), em2("Gamma", 0), em3("Epsilon", -1);
    std::cout << em1.print(0);
    std::cout << em2.print(0);
    std::cout << em3.print(0);
    return 0;
}    

Output:


Hello, my name is Alpha. I am male.
Hello, my name is Beta. I am female.
Hello, my name is Delta. I am female.
Hello, my name is Gamma. I am male.
Hello, my name is Epsilon. I am transgender.

Question 2 - Operator Overloading

Implement a class named RealTime with representation HH:MM:SS. Design and implement appropriate constructors.

Overload the following operators:

    +	 Addition e.g. myRealTime + yourRealTime
    ++	 Post-Increment e.g. myRealTime++
    ++	 Pre-Increment e.g. ++RealTime 

Provide comments in your code and proper indentation, so that it is easy to read.

Solution:


#include <iostream>
#include <iomanip>

class RealTime
{
private:
    int hr, min, sec;

public:
    RealTime();
    RealTime(int, int, int);
    ~RealTime();
    RealTime operator+(RealTime const &);
    RealTime operator++();
    RealTime operator++(int);
    friend std::ostream &operator<<(std::ostream &, RealTime const &);
};

RealTime::RealTime()
{
    hr = min = sec = 0;
}

RealTime::RealTime(int hr, int min, int sec)
{
    this->hr = hr;
    this->min = min;
    this->sec = sec;
}

RealTime::~RealTime()
{
}

RealTime RealTime::operator+(RealTime const &rt)
{
    RealTime temp;
    temp.sec = this->sec + rt.sec;
    temp.min = this->min + rt.min + temp.sec / 60;
    temp.sec %= 60;
    temp.hr = this->hr + rt.hr + temp.min / 60;
    temp.min %= 60;
    return temp;
}

RealTime RealTime::operator++()
{
    ++sec;
    min = min + sec / 60;
    sec %= 60;
    hr = hr + min / 60;
    min %= 60;
    return *this;
}

RealTime RealTime::operator++(int)
{
    RealTime temp(hr, min, sec);
    sec++;
    min = min + sec / 60;
    sec %= 60;
    hr = hr + min / 60;
    min %= 60;
    return temp;
}

std::ostream &operator<<(std::ostream &os, RealTime const &rt)
{
    return os << std::setfill('0') << std::setw(2) << rt.hr << ":"
                << std::setfill('0') << std::setw(2) << rt.min << ":"
                << std::setfill('0') << std::setw(2) << rt.sec;
}

int main(int argc, char const *argv[])
{
    RealTime myRealTime(7, 2, 5), yourRealTime(12, 34, 56);
    RealTime resRealTime = myRealTime + yourRealTime;
    std::cout << "My Real Time = " << myRealTime << std::endl;
    std::cout << "Your Real Time = " << yourRealTime << std::endl;
    std::cout << "Total Real Time = " << resRealTime << std::endl;
    std::cout << "Prefix Add Real Time = " << ++myRealTime << std::endl;
    std::cout << "Postfix Add Real Time = " << yourRealTime++ << std::endl;
    std::cout << yourRealTime << std::endl;
    return 0;
}    

Output:


My Real Time = 07:02:05
Your Real Time = 12:34:56
Total Real Time = 19:37:01
Prefix Add Real Time = 07:02:06
Postfix Add Real Time = 12:34:56
12:34:57

Share:

Programming with C++ - Day3 || Wong Edition || B.Tech Diaries

Lab #3 - Classes

Question 1 - Rectangle

Implement the Rectangle class according to the given Class Diagram.

Rectangle
- length : int
- width: int
- colour : string
+ getArea() : int
+ print() : string
+ compare(Rectangle r1) : int

Write a constructor which takes as input the length and width of a Rectangle instance. In the default constructor, initalise the length and width to 0;

The function compare returns

    0, if the Rectangle instances are of the same size,
    1, if r1 is larger
    -1, if r1 is smaller 

The function print gives the dimensions, colour and area of the Rectangle instance.

In the main function of Rectangle, obtain and validate user input for the Rectangle's dimensions and colour. Create 2 Rectangle instances and compare their area. [Hint: check for type and negative numbers]

Solution:


    #include <iostream>
    #include <sstream>

    class Rectangle
    {
    private:
        int length, breadth;
        std::string colour;

    public:
        Rectangle();
        Rectangle(int, int, std::string);
        ~Rectangle();
        int getArea();
        std::string print();
        int compare(Rectangle);
    };

    Rectangle::Rectangle()
    {
        length = 0;
        breadth = 0;
        colour = "";
    }

    Rectangle::Rectangle(int length, int breadth, std::string colour)
    {
        this->length = length;
        this->breadth = breadth;
        this->colour = colour;
    }

    Rectangle::~Rectangle()
    {
    }

    int Rectangle::getArea()
    {
        return this->length * this->breadth;
    }

    std::string Rectangle::print()
    {
        std::stringstream ps;
        ps << "nLength: " << this->length
        << "nBreadth: " << this->breadth
        << "nColour: " << this->colour
        << "nArea: " << this->getArea() << std::endl;
        return ps.str();
    }

    int Rectangle::compare(Rectangle rect)
    {
        if (this->getArea() > rect.getArea())
            return 1;
        else if (this->getArea() < rect.getArea())
            return -1;
        return 0;
    }

    int main(int argc, char const *argv[])
    {
        int len, br;
        std::string col;

        // std::cout << "Enter dimensions for Rectangle 1:n"
        //           << "Length:";
        while (std::cin >> len)
        {
            if (len > 0)
                break;
            if (len <= 0)
                std::cout << "Length should be greater than 0n";
        }
        // std::cout << "Breadth:";
        while (std::cin >> br)
        {
            if (br > 0)
                break;
            if (br <= 0)
                std::cout << "Breadth should be greater than 0" << std::endl;
        }
        // std::cout << "Color:";
        std::cin.ignore();
        std::cin >> col;
        Rectangle rect1(len, br, col);

        // std::cout << "Enter dimensions for Rectangle 2:n"
        //           << "Length:";
        while (std::cin >> len)
        {
            if (len > 0)
                break;
        }
        // std::cout << "Breadth:";
        while (std::cin >> br)
        {
            if (br > 0)
                break;
        }
        // std::cout << "Color:";
        std::cin.ignore();
        std::cin >> col;
        Rectangle rect2(len, br, col);

        std::cout << "Rectangle 1n"
                << rect1.print() << std::endl;
        std::cout << "Rectangle 2n"
                << rect2.print() << std::endl;

        if (rect1.compare(rect2) == 1)
            std::cout << "Rectangle 1 is bigger than Rectangle 2" << std::endl;
        else if (rect1.compare(rect2) == -1)
            std::cout << "Rectangle 2 is bigger than Rectangle 1" << std::endl;
        else
            std::cout << "Rectangle 1 and Rectangle 2 are equal" << std::endl;

        return 0;
    }  

Output:


    12
    54
    Red
    24
    32
    Green
  
    Rectangle 1
    
    Length: 12
    Breadth: 54
    Colour: Red
    Area: 648
    
    Rectangle 2
    
    Length: 24
    Breadth: 32
    Colour: Green
    Area: 768
    
    Rectangle 2 is bigger than Rectangle 1

Question 2 - Student Records

In a UML Diagram, design a Student class with the following attributes:-

    name (max 30 characters)
    rollNumber (between 1 and 260)
    mobileNumber (10 digits)
    emailAddress (must contain '@' and then '.')
    attendance (between 0 and 1, where 1 is 100% attendance)

Provide the following functions:-

    getName, getRollNumber, ...
    setName, setRollNumber, ...
    print, which outputs the Student details in a comma-delimited string

    e.g. Donald Duck, 123, 1234567890, donald@duck.com, 0.00

The Student records are managed by the StudentManager class, which holds the main() loop.

StudentManager
- studentList:Student[10]
* getStudentInput:Student
* sortByRollNumber:Student[]
* sortByAttendance:Student[]
* printAttendanceReport(filename, sortBy:bool) : bool

The function printAttendanceReport outputs the list of students to a user-specified filename. If sortBy is true, the student list will be sorted by roll number, else the student list will be sorted by attendance (followed by roll number).

Provide the following user menu:

  1. Enter Student Details
  2. Update Student Mobile Number
  3. Update Student Email Address
  4. Print Attendance Report by Roll Number
  5. Print Attendance Report by Attendance
  6. Exit

Solution:


#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>

class Student
{
private:
    std::string name;
    int rollNumber;

public:
    long mobileNumber;
    std::string emailAddress;
    double attendance;

    Student();
    ~Student();
    std::string getName();
    int getRollNumber();
    void setName(std::string);
    void setRollNumber(int);
    std::string print();
};

Student::Student()
{
    this->name = "";
    this->rollNumber = 0;
    this->mobileNumber = 0;
    this->emailAddress = "";
    this->attendance = 0;
}

Student::~Student()
{
}

std::string Student::getName()
{
    return name;
}

int Student::getRollNumber()
{
    return rollNumber;
}

void Student::setName(std::string name)
{
    this->name = name;
}

void Student::setRollNumber(int rollNumber)
{
    this->rollNumber = rollNumber;
}

std::string Student::print()
{
    std::stringstream ps;
    ps << name << "," << rollNumber << "," << mobileNumber << "," << emailAddress << "," << attendance;
    return ps.str();
}

class StudentManager
{
private:
    std::vector<Student> studentList;

public:
    StudentManager();
    ~StudentManager();
    Student getStudentInput();
    void addStudent(Student);
    bool isEmpty();
    Student getStudent(int);
    bool setStudent(int, Student);
    std::vector<Student> sortByRollNumber();
    std::vector<Student> sortByAttendance();
    bool printAttendanceReport(std::string, bool);
};

StudentManager::StudentManager()
{
}

StudentManager::~StudentManager()
{
}

void StudentManager::addStudent(Student student)
{
    studentList.push_back(student);
}

Student StudentManager::getStudent(int rollno)
{
    for (int i = 0; i < studentList.size(); i++)
    {
        if (studentList[i].getRollNumber() == rollno)
        {
            return studentList[i];
        }
    }
    return Student();
}

bool StudentManager::setStudent(int rollno, Student student)
{
    for (int i = 0; i < studentList.size(); i++)
    {
        if (studentList[i].getRollNumber() == rollno)
        {
            studentList[i] = student;
            return true;
        }
    }
    return false;
}

bool StudentManager::isEmpty()
{
    return studentList.empty();
}

Student StudentManager::getStudentInput()
{
    Student student;
    std::string name;
    int rollNumber;
    long mobileNumber;
    std::string emailAddress;
    double attendance;
    std::cout << "Enter name: ";
    std::cin.ignore();
    std::getline(std::cin, name);
    std::cout << "Enter roll number: ";
    std::cin >> rollNumber;
    std::cout << "Enter mobile number: ";
    std::cin >> mobileNumber;
    std::cout << "Enter email address: ";
    std::cin.ignore();
    std::cin >> emailAddress;
    std::cout << "Enter attendance: ";
    std::cin >> attendance;
    student.setName(name);
    student.setRollNumber(rollNumber);
    student.mobileNumber = mobileNumber;
    student.emailAddress = emailAddress;
    student.attendance = attendance;
    return student;
}

std::vector<Student> StudentManager::sortByRollNumber()
{
    int N = this->studentList.size();
    std::vector<Student> studentList(N);
    for (int i = 0; i < N; i++)
    {
        studentList[i] = this->studentList[i];
    }
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N - i - 1; j++)
        {
            if (studentList[j].getRollNumber() > studentList[j + 1].getRollNumber())
            {
                std::swap(studentList[j], studentList[j + 1]);
            }
        }
    }
    return studentList;
}

std::vector<Student> StudentManager::sortByAttendance()
{
    int N = this->studentList.size();
    std::vector<Student> studentList(N);
    for (int i = 0; i < N; i++)
    {
        studentList[i] = this->studentList[i];
    }
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N - i - 1; j++)
        {
            if (studentList[j].attendance > studentList[j + 1].attendance)
            {
                std::swap(studentList[j], studentList[j + 1]);
            }
            else if ((studentList[j].attendance == studentList[j + 1].attendance) && (studentList[j].getRollNumber() > studentList[j + 1].getRollNumber()))
            {
                std::swap(studentList[j], studentList[j + 1]);
            }
        }
    }
    return studentList;
}

bool StudentManager::printAttendanceReport(std::string filename, bool sortBy)
{
    std::ofstream report;
    report.open(filename);

    std::vector<Student> studentList;

    if (sortBy)
    {
        studentList = sortByRollNumber();
    }
    else
    {
        studentList = sortByAttendance();
    }

    for (Student stud : studentList)
    {
        report << stud.print() << std::endl;
    }

    report.close();

    return true;
}

int main(int argc, char const *argv[])
{
    StudentManager mngr;
    int ch = 0;
    int rollNumber;
    Student stud;
    std::string filename;

    while (ch != 5)
    {
        std::cout << "n======Student Manager======" << std::endl;
        std::cout << "0.  Enter Student Detailsn"
                  << "1.  Update Student Mobile Numbern"
                  << "2.  Update Student Email Addressn"
                  << "3.  Print Attendance Report by Roll Numbern"
                  << "4.  Print Attendance Report by Attendancen"
                  << "5.  Exitn"
                  << std::endl;
        std::cout << "Enter your choice: ";
        std::cin >> ch;

        switch (ch)
        {
        case 0:
            mngr.addStudent(mngr.getStudentInput());
            break;
        case 1:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }
            std::cout << "Enter roll number: ";
            std::cin >> rollNumber;
            stud = mngr.getStudent(rollNumber);
            if (stud.getRollNumber() == 0)
            {
                std::cout << "Student not found"
                          << std::endl;
                break;
            }
            std::cout << "Enter Mobile number: ";
            std::cin >> stud.mobileNumber;
            mngr.setStudent(rollNumber, stud);
            break;
        case 2:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }
            std::cout << "Enter roll number: ";
            std::cin >> rollNumber;
            stud = mngr.getStudent(rollNumber);
            if (stud.getRollNumber() == 0)
            {
                std::cout << "Student not found"
                          << std::endl;
                break;
            }
            std::cout << "Enter Email address: ";
            std::cin.ignore();
            std::cin >> stud.emailAddress;
            mngr.setStudent(rollNumber, stud);
            break;

        case 3:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }

            std::cout << "Enter filename: ";
            std::cin.ignore();
            std::getline(std::cin, filename);
            mngr.printAttendanceReport(filename, true);
            break;

        case 4:
            if (mngr.isEmpty())
            {
                std::cout << "No students entered yet"
                          << std::endl;
                break;
            }

            std::cout << "Enter filename: ";
            std::cin.ignore();
            std::getline(std::cin, filename);
            mngr.printAttendanceReport(filename, false);
            break;

        case 5:
            std::cout << "Exiting..." << std::endl;
            break;

        default:
            std::cout << "Invalid choice" << std::endl;
            break;
        }
    }

    return 0;
}

Output:


    ======Student Manager======
    0.  Enter Student Details
    1.  Update Student Mobile Number
    2.  Update Student Email Address
    3.  Print Attendance Report by Roll Number
    4.  Print Attendance Report by Attendance
    5.  Exit
    
    Enter your choice: 0
    Enter name: Bhola
    Enter roll number: 45
    Enter mobile number: 32
    Enter email address: bholaeatschola@gmail.com
    Enter attendance: 78
    
    ======Student Manager======
    0.  Enter Student Details
    1.  Update Student Mobile Number
    2.  Update Student Email Address
    3.  Print Attendance Report by Roll Number
    4.  Print Attendance Report by Attendance
    5.  Exit
    
    Enter your choice: 3
    Enter filename: report
    
    ======Student Manager======
    0.  Enter Student Details
    1.  Update Student Mobile Number
    2.  Update Student Email Address
    3.  Print Attendance Report by Roll Number
    4.  Print Attendance Report by Attendance
    5.  Exit
    
    Enter your choice: 5
    Exiting...

File Contents:

Bhola,45,32,bholaeatschola@gmail.com,78
Share:

Programming with C++ - Day2 || Wong Edition || B.Tech Diaries

Lab #2 - C++ Basics (Pointers, FileIO)

Question 1 - Outlet Sales Report

Modify Lab 1 Question 2 to use the following functions:-


    /*********************************************************************/
    /* getSales obtains user input for the outlets                       */
    /* aptr - pointer to an array of double                              */
    /* size - size of array                                              */
    /*********************************************************************/
    void getSales(double * aptr, int size);


    **********************************************************************/
    /* calcTotalSales calculates the total sales for all outlets         */
    /* aptr - pointer to an array of double                              */
    /* size - size of array                                              */
    /* returns total as double                                           */
    /*********************************************************************/
    double calcTotalSales(const double * aptr, int size);

Save your sales report by using the following code snippet:-

    #include <fstream>
    ...
    
        ofstream outfile;
    
        outfile.open("report.txt");
        outfile << ... << endl;
        ....
        outfile.close();
    
        cout << "File written successfully" << endl;

Solution:


    #include <iostream>
    #include <iomanip>
    #include <fstream>
    
    void printbar(std::string store, double sales, double sales_max, std::ofstream &outfile)
    {
        outfile << std::setw(12) << std::left << store << ": \t";
        for (int j = 0; j < int(sales * 50.0 / sales_max); j++)
        {
            outfile << "*";
        }
        outfile << std::endl;
    }
    
    void getSales(double *aptr, int size)
    {
        for (int i = 0; i < size; i++)
        {
            // std::cout << "Enter sales for day " << i + 1 << ": ";
            std::cin >> aptr[i];
        }
    }
    
    double calcTotalSales(const double *aptr, int size)
    {
        double total = 0;
        for (int i = 0; i < size; i++)
        {
            total += aptr[i];
        }
        return total;
    }
    
    int main(int argc, char const *argv[])
    {
        std::string date = "July 22, 2019", manager = "Tutu Pal";
        std::string store_names[5] = {"City Centre", "Park Street", "Rajarhat", "South City", "Dum Dum"};
    
        std::ofstream outfile;
    
        int size = 5, max = 0;
        double *aptr = new double[size];
    
        getSales(aptr, size);
    
        for (int i = 0; i < size; i++)
        {
            if (aptr[i] > aptr[max])
            {
                max = i;
            }
        }
    
        outfile.open("report.txt");
    
        outfile << "\nDate:\t" << date << "\nName of Sales Manager:\t" << manager << "\n"
                << std::endl;
    
        for (int i = 0; i < size; i++)
        {
            printbar(store_names[i], aptr[i], aptr[max], outfile);
        }
    
        outfile << "\nThe store with the top sales on " << date << " is " << store_names[max] << std::endl;
    
        outfile << "\nThe total sales is $";
        outfile << std::setprecision(2) << std::fixed << calcTotalSales(aptr, size)
                << ".\n"
                << std::endl;
    
        outfile.close();
    
        std::cout << "File written successfully" << std::endl;
        return 0;
    }   

Input:


456
652 
64
12
35
File written successfully

Output:


Date:	July 22, 2019
Name of Sales Manager:	Tutu Pal

City Centre : 	**********************************
Park Street : 	**************************************************
Rajarhat    : 	****
South City  : 	
Dum Dum     : 	**

The store with the top sales on July 22, 2019 is Park Street

The total sales is $1219.00.

Question 2 - Country List

Read a list of countries from the file countries.txt, and sort them in reverse alphabetical order, i.e. Zambia first and Australia last.


    #include <fstream>
    ...

        ifstream infile;
        int number;

        infile.open("numbers.txt");
        while (!infile.eof()) {
            infile >> number;
            cout << number << endl;
        }

        infile.close();

Handle the situation where the stipulated filename cannot be found.

Solution:


    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <algorithm>
    
    int main(int argc, char const *argv[])
    {
        std::ifstream infile;
        std::vector<std::string> countries;
        std::string country;
    
        int i, j;
    
        infile.open("countries.txt");
    
        if (infile.fail())
        {
            std::cout << "Error opening file" << std::endl;
            return 1;
        }
    
        while (std::getline(infile, country))
        {
            countries.push_back(country);
        }
        infile.close();
    
        for (int i = 0; i < countries.size(); i++)
        {
            for (int j = 0; j < countries.size() - i - 1; j++)
            {
                if (std::lexicographical_compare(countries[j].begin(), countries[j].end(), countries[j + 1].begin(), countries[j + 1].end()))
                {
                    std::swap(countries[j], countries[j + 1]);
                }
            }
        }
    
        for (std::string country : countries)
        {
            std::cout << country << std::endl;
        }
    
        return 0;
    }    

Input:


United Kingdom
Italy
Brazil
Russia
South Africa
Chile
Portugal
Greece
Kenya
Egypt
Zambia
Malaysia
Japan
Australia

Output:


Zambia
United Kingdom
South Africa
Russia
Portugal
Malaysia
Kenya
Japan
Italy
Greece
Egypt
Chile
Brazil
Australia    

Question 3 - Vowels & Consonants

Write a function that returns the number of vowels in a given string. Write another function that returns the number of consonants in a given string.

Use the 2 functions to perform the following:-

  1. The user is asked to enter a string.
  2. The program displays the following menu:
    • Count the number of vowels in the string
    • Count the number of consonants in the string
    • Count both the vowels and consonants in the string
    • Enter another string
    • Exit the program
  3. The program performs the operation selected by the user and repeats until the user selects E to exit the program.

Solution:


    #include <iostream>

    int no_of_vowels(std::string str)
    {
        int count = 0;
        for (char c : str)
        {
            if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
                count++;
        }
        return count;
    }
    int no_of_consonants(std::string str)
    {
        int count = 0;
        for (char c : str)
        {
            if (!(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'))
                count++;
        }
        return count;
    }
    
    int main(int argc, char const *argv[])
    {
        std::string s;
        std::cout << "Enter a string:" << std::endl;
        std::getline(std::cin, s);
        char ch = '';
        while (ch != 'E')
        {
            std::cout << "nOptions:"
                      << "nA) Count the number of vowels in the string"
                      << "nB) Count the number of consonants in the stringnC) Count both the vowels and consonants in the string"
                      << "nD) Enter another string"
                      << "nE) Exit the program"
                      << "nEnter your choice: ";
            std::cin >> ch;
            switch (ch)
            {
            case 'A':
                std::cout << "The number of vowels in the string is: " << no_of_vowels(s) << std::endl;
                break;
            case 'B':
                std::cout << "The number of consonants in the string is: " << no_of_consonants(s) << std::endl;
                break;
            case 'C':
                std::cout << "The number of vowels in the string is: " << no_of_vowels(s) << std::endl;
                std::cout << "The number of consonants in the string is: " << no_of_consonants(s) << std::endl;
                break;
            case 'D':
                std::cout << "Enter a string:" << std::endl;
                std::cin.ignore();
                std::getline(std::cin, s);
                break;
            case 'E':
                std::cout << "Exiting the program..." << std::endl;
                break;
            default:
                std::cout << "Invalid choice. Please try again." << std::endl;
                break;
            }
        }
        return 0;
    }

Output:


Enter a string:
React component that displays a spinner via spin.js until your component is loaded.

Options:
A) Count the number of vowels in the string
B) Count the number of consonants in the string
C) Count both the vowels and consonants in the string
D) Enter another string
E) Exit the program
Enter your choice: A
The number of vowels in the string is: 25

Options:
A) Count the number of vowels in the string
B) Count the number of consonants in the string
C) Count both the vowels and consonants in the string
D) Enter another string
E) Exit the program
Enter your choice: E
Exiting the program...

Share: