Thinking in C++

My C++ code snips.

Archive for the ‘C++’ Category

C++ codes

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

Advertisements

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 »