Thinking in C++

My C++ code snips.

Calendar in C.

Posted by Abhi on July 7, 2012

I just finished writing the code for printing a calendar for a given year in C. Thought it might be useful to someone.

/***************************************
Program to print the calendar of a given
year. You also have to enter the starting
day of that year in words.

Written by Abijeet. 7-7-2012

****************************************/

#include
#include

#define DAYS 7
#define WEEKS 5
#define MAX 30
#define MONTHS 12

int isLeapYear(int);
int getStartingDay(const char*);
int noOfDaysInMonth(int);
int printMonth(int,int,int,int);
char* getNameOfMonth(int);

int main()
{
    int monthNo, currentDay, year, startDay, lastDay;   // startDay is starting day, lastDay is the last day of the month.
    int flagLeap,errNo;
    char startingDay[MAX],ans;
    do
    {
        errNo=0;
        printf("Enter the year: ");
        scanf("%d",&year);
        // Determining whether the year is a leap year.
        flagLeap = isLeapYear(year);

        // Determining the starting day of the week
        do
        {
            if(errNo>0)
                printf("\nWrong day entered, please enter the starting day as Sunday or Monday or Tuesday or any other day of the week.\n\n");

            printf("Please enter the starting day of the year: ");
            scanf("%s",&startingDay);

            startDay = getStartingDay(startingDay);
            ++errNo;

        }while(startDay == -1);
        //printf("%d %d %d",startDay,flagLeap,noOfDaysInMonth(7));

        // Prints the months of the year
        for(monthNo=0;monthNo<MONTHS;++monthNo)
        {
            // For Feburary in which the year is a leap year.
            if((monthNo == 1) && flagLeap)
            {
                lastDay = printMonth(monthNo,startDay,29,year);
            }
            else
            {
                lastDay=printMonth(monthNo,startDay,noOfDaysInMonth(monthNo),year);
            }
            // Calculating the starting day of the next month.
            if(lastDay == 6)
                startDay = 0;
            else
                startDay = lastDay + 1;
        }
        printf("Do you want to display the calendar for another year? (Y/N) : __\b\b");
        scanf("%s",&ans);
    }while(ans=='y'||ans=='Y');

    printf("\nThanks for using..Bye!\n\n");

    return 0;
}

/**********************************
Function to check if the year is a
leap year. Return 1 if it is a leap
year else Returns 0.

**********************************/

int isLeapYear(int year)
{
    if((year%4==0)&&(year%100!=0)||(year%400==0))
        return 1;
    return 0;
}

/***************************************
Function to return the number of the day
in the week when the user enters the
string. For example, will return 0 for
Sunday, 1 for Monday, 2 for Tuesday and
so on.....

****************************************/

int getStartingDay(const char* nameOfDay)
{
    char nameOfDaysOfWeek[DAYS][MAX] = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"};
    char nameOfDaysOfWeekInSmall[DAYS][MAX] = {"sunday","monday","tuesday","wednesday","thursday","friday","saturday"};
    int i;
    for(i=0;i<DAYS;++i)
    {
        if(strcmp(nameOfDay,nameOfDaysOfWeek[i])==0 || strcmp(nameOfDay,nameOfDaysOfWeekInSmall[i])==0)
            return i;
    }
    return -1;
}

/**********************************
Function to return the number of
days in a month. Returns 28 for
Feburary by default.

**********************************/

int noOfDaysInMonth(int monthNum)
{
    int dayMonth[MONTHS][1] = {{31},{28},{31},{30},{31},{30},{31},{31},{30},{31},{30},{31}};

    return *dayMonth[monthNum];
}

/***************************************
Core of the program. This function takes
month number, starting day, and total days
in a month as input and displays the month.
It also returns the name of the last day of
the month so that the calling function can
use it to calculate the first day of the
next month. Also takes the year as input
and prints it.

****************************************/

int printMonth(int month,int startDay,int noOfDays,int year)
{
    int currentDay=1,calendar[WEEKS][DAYS],currentNameOfDay;
    int row,col;
    char nameOfMonth[MAX];

    // Initializing all the array elements to 0

    for(row=0;row<WEEKS;++row)
    {
        for(col=0;col<DAYS;++col)
        {
            calendar[row][col]=0;
        }
    }
    row = 0;
    // Filling up the array with dates
    while(currentDay     {
        for(col = 0;colnoOfDays)
                break;

        }
        ++row; // Moving to the next row of the array.
    }
    currentNameOfDay = col;

    /*
    Stores where the current month ended, and returns it to the calling functions so that it
    can calculate the starting day of the next month!
    */

    // Now printing the calendar!!
    strcpy(nameOfMonth,getNameOfMonth(month));
    printf("\n%s, %d\n__________________________________________________________________\n",nameOfMonth,year);

    // Printing the days of the week....
    printf("\n\tSun\tMon\tTue\tWed\tThu\tFri\tSat\n\n");

    for(row=0; row    {
        for(col=0;col < DAYS;++col)
        {
        /*
        We initialized the calendar array to 0, now when printing it we do not
        want to display the 0's. So if the value is 0, we print a tab space and
        continue.
        */
            if(calendar[row][col] == 0)
            {
                printf(" \t");
                continue;
            }
            printf("\t%d",calendar[row][col]);
        }
        printf("\n");
    }
    printf("\n\n\n");

    return currentNameOfDay;
}

/***************************************
Takes the month number as input and
returns the name of the month.

***************************************/

char* getNameOfMonth(int month)
{
    static char monthNames[MONTHS][MAX]={"January","Feburary","March","April","May","June","July","August","September","October","November","December"};
    return monthNames[month];
}

Posted in C Programming Language | Leave a Comment »

Input bullet-proofing in C++

Posted by Abhi on June 8, 2012

Yes, it’s a lot of code for something that should be much simpler but it’s the only fool proof way I know off to make sure that the program accepts only integers.


#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

int ReadInt(const std::string &prompt)
{
    std::stringstream strm;
    std::string s;
    int val;
    bool flag;
    while(std::cout<<prompt && std::getline(std::cin,s))
    {
        flag = true;
        for(std::string::size_type index = 0; index!= s.size(); ++index)
        {
            if(!isdigit(s[index]))			// isdigit() included in cctype
            {
                flag=false;
                std::cout<<"Invalid input; Please try again.\n";
                break;
            }
        }
        if(!flag)
            continue;
        break;
    }
    strm.str(s);	// Copying the string into the stream.
    strm>>val;		// reading the stream into an integer.
    return val;
}

Usage:


#include "readInt.h"
#include <iostream>

using std::cout;
using std::endl;

int main(int argc, char** argv) {

    int a=ReadInt("Please enter the value of a;");
    int b=ReadInt("Please enter the value of b;");
    cout<<a*b<<endl;

    return 0;
}

Example:


Please enter the value of a;5t
Invalid input; Please try again.
Please enter the value of a;sa sa sa
Invalid input; Please try again.
Please enter the value of a;55
Please enter the value of b;2
110

Posted in C++ | Leave a Comment »

Vector to map C++

Posted by Abhi on April 16, 2012

Here is a code snippet to insert a vector into a map. The function takes a vector and a map<string, vector > as argument. The first element of the vector is treated as the key, and the rest is the value. This should be useful when retrieving unknown number of values from a file [settings for example].

  • Read the file, one line at a time.
  •  Split the line based on whatever divider you choose and store it in a vector of string.
  •  Then use this function to insert the vector into a map.

Header:

#ifndef vectorMap_H
#define vectorMap_H

#include <string>
#include <map>
#include <vector>

void vectorMap(const std::vector<std::string> &, std::map<std::string,std::vector<std::string> > &);

#endif

Implementation:

#include "vectorMap.h"

using std::map;
using std::string;
using std::vector;

typedef vector<string> vec_str;
typedef map<string, vector<string> > map_str;

void vectorMap(const std::vector<std::string> &v_str, std::map<std::string,std::vector<std::string> > &m_str)
{
 string key;
 for(vec_str::const_iterator iter= v_str.begin(); iter != v_str.end(); ++iter )
 {
 if(iter == v_str.begin())
 {
 key = *iter;
 continue;
 }
 m_str[key].push_back(*iter);
 }
}

Posted in C++ | Tagged: , | Leave a Comment »

File To Map Input/Output C++

Posted by Abhi on April 16, 2012

Here are a couple of function that will allow you to write a map to a file that you specify. Currently the type of the map supported is map. The data in the file is separated by “|”. For example: key|value.

This file uses the splitString() function I wrote earlier to split the string while reading into the map from the file.

The header file :


#ifndef FileMapIO_H
#define FileMapIO_H

#include <map>
#include <string>

bool mapToFile(const std::string &, const std::map<std::string,std::string> &);
bool fileToMap(const std::string &, std::map<std::string,std::string> &);

#endif

Implementation :

#include "fileMapIO.h"
#include <string>
#include <map>
#include <fstream>
#include <vector>
#include "splitString.h"

using std::string;
using std::map;
using std::ofstream;
using std::ifstream;
using std::vector;

typedef map<string,string> stringMap;

bool mapToFile(const string &filename,const stringMap &fileMap)		//Write Map
{
	ofstream ofile;
	ofile.open(filename.c_str());
	if(!ofile)
	{
		return false;			//file does not exist and cannot be created.
	}
	for(stringMap::const_iterator iter= fileMap.begin(); iter!=fileMap.end(); ++iter)
	{
		ofile<<iter->first<<"|"<<iter->second;
		ofile<<"\n";
	}
	return true;
}
bool fileToMap(const std::string &filename, stringMap &fileMap)  //Read Map
{
	ifstream ifile;
	ifile.open(filename.c_str());
	if(!ifile)
		return false;  	//could not read the file.
	string line;
	string key;
	vector<string> v_str;
	while(ifile>>line)
	{
		splitString(v_str,line,'|');
		for(vector<string>::iterator iter = v_str.begin();;++iter)		//First vector element is the key.
		{
			if(iter == v_str.begin())
			{
				fileMap[*iter]="Unavailable";
				key= *iter;
				continue;
			}
			fileMap[key]= *iter;
			break;
		}
	}
	return true;
}

Posted in C++ | Tagged: , , , , , | Leave a Comment »

Personal Dictionary App

Posted by Abhi on February 11, 2012

Over the past couple of days, I’ve been busy writing a small personal dictionary program that will allow me to add words that I’ve learnt to a file and then access them later if need be.

You can add words using the “add <word> <meaning> <notes>” command via the linux terminal. <notes> is optional. You can then view the words that have been added using the “define <word>” command. To easily view all the words that have been added to the file, I created the “exportdict” command that transforms the file into a cleanly formatted html document that can be viewed through your preferred browser.

Commands

HTML Screenshot

The entire program took me about two days to write. It employs a few basic checks such as – not allowing multiple similar entries but nothing major. The database file that the program uses is called dict-data.rog and it will be created in the same folder as the executable. Now this application isn’t exactly fault tolerent so if you make any changes to the databse file, make sure that the format is kept intact. If that is not possible then simply delete the file. Needless to say your data will be lost, hence it might be a good idea to back it up first.

General Format of the data in the database: “<entry>|<value>|<notes>” where “|” is the seperator.

Unless you want your database to be screwed up I suggest not adding “|” in your entries. In case incompatible data is found, the program will inform you of the entry which contains the incompatible data.

Currently the only way to edit existing entries is to edit them manually by opening the database file. I may write a small add-on to remedy that depending on whether or not I need it.

The executables that I’ve provided will run on a 64-bit Linux machines. I’ve also provided the source code so if you wish you can download and compile them for your platform. They should run on Windows too but I’m not entirely sure.

Feel free to make changes to the source code, and any suggestions. If you use the program and find any bugs, let me know.

Source Code : Download Here

Executables : Download Here

Posted in C++, Projects | Tagged: , | 2 Comments »

C++ Split String

Posted by Abhi on February 9, 2012

Here is a simple string split function that I wrote a while back. The function takes a string such as “How.Are.You.”, a divider – “.” and a reference to a vector of strings as input. The vector is then filled with the strings after they have been split.

#include <string>
#include <vector>

using std::vector;
using std::string;

void splitString(vector<string> &v_str,const string &str,const char ch)
{
	string sub;
	string::size_type pos = 0;
	string::size_type old_pos = 0;
	bool flag=true;
	
	while(flag)
	{
		pos=str.find_first_of(ch,pos);
		if(pos == string::npos)
		{
			flag = false;
			pos = str.size();
		}
		sub = str.substr(old_pos,pos-old_pos);  // Disregard the '.'
		v_str.push_back(sub);
		old_pos = ++pos;
	}
}

Usage:

#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include "splitString.h"       // Header file for the splitString function.

using std::vector;
using std::string;
using std::cout;

int main()
{
	string str= "How.Are.You";	// String to be split.
	char ch = '.';			// The divider.
	vector<string> v_str;		// Vector to store the divided strings.

	splitString(v_str,str,ch);

	for(vector<string>::iterator iter= v_str.begin();iter!=v_str.end();++iter)
		cout<<*iter<<"\n";
	return 0;
}

Output:

How
Are
You

Remember to put the necessary #include if you decide to put the codes in separate files.

Posted in C++ | Tagged: , , , | 1 Comment »

C++ Trim

Posted by Abhi on February 8, 2012

C++ standard library lacks a trim() function similar to what Java provides. Here is a simple function in C++ which can achieve similar results.

#include <string>

std::string trim(const std::string& str)
{
	using std::string;
	string::size_type pos = str.find_first_not_of(" ");
	string::size_type pos1 = str.find_last_not_of(" ");
	string trimmed = str.substr(pos,pos1-pos+1);
	
	return trimmed;
}

Usage :

#include <iostream>
#include <string>
int main()
{
	std::string mystr = trim(" hello  ");
	std::cout<<"|";
	std::cout<<mystr;
	std::cout<<"|";
}

Output :

|hello|

Pardon me for the lack of tabs, apparently WordPress does not allow you to add tabs to your posts.

Edit: My bad. WordPress does provide support to paste code. Read more here

Posted in C++ | Tagged: , , | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.