Week #14 Challenge: C++

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • Last »

67 Replies - 27865 Views - Last Post: 13 October 2010 - 08:11 AM

#16 josh06  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 14
  • View blog
  • Posts: 139
  • Joined: 27-October 06

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 03:00 AM

#include <cstdlib>
#include <iostream>
 
using namespace std;
 
int main()
{
    double num;
    double num2;
    char choice;
    for (;;)/>{
     do {
    cout<<"Welcome to thejoshcalculator. V1.5\n";
    cout<<"Please choose an option by entering the number, press q to quit\n";
    cout<<"1 - Addition\n";
    cout<<"2 - Subtraction\n";
    cout<<"3 - Division\n";
    cout<<"4 - Multiplication\n";
    cout<<"5 - Help\n";
    cout<<"6 - About This Program\n";
    cout<<"7 - Updates to this program\n";
    cin>>choice;
    } while ( choice < '1' || choice > '7' && choice != 'q');
    if (choice == 'q') break;
    switch (choice) {
           case '1':
                cout<<"Please enter a number\n";
                cin>>num;
                cout<<"Another number to be added\n";
                cin>>num2;
                cout<<num + num2;
                cout<<"\n";
                break;
           case '2':
                cout<<"Please enter a number\n";
                cin>>num;
                cout<<"Another number to be subtracted\n";
                cin>>num2;
                cout<<num - num2;
                cout<<"\n";
                break;
           case '3':
                cout<<"Please enter a number\n";
                cin>>num;
                cout<<"Another one to be divided\n";
                cin>>num2;
                cout<<num / num2;
                cout<<"\n";
                break;
           case '4':
                cout<<"Please enter a number\n";
                cin>>num;
                cout<<"Another one to be multiplied\n";
                cin>>num2;
                cout<<num * num2;
                cout<<"\n";
                break;
           case '5':
                cout<<"This is a simple calculator made by me - Josh.\n";
                cout<<"To select an option, type the number next to the option and press enter\n";
                cout<<"E.G. for division, you would type 3 and press enter.\n";
                cout<<"\n";
                break;
           case '6':
                cout<<"thejoshcalculator, made by Joshua Griggs - Copyright 2007. :)/>\n";
                cout<<"Feedback would be nice - joshieboy06@hotmail.com also, what programmes\n";
                cout<<"do people need. Please give me ideas for programs. Bye!!\n";
                cout<<"\n";
                break;
           case '7':
                cout<<"Updates include:  -double variable instead of int, so that decimals can be used.\n";
                cout<<"                  -do while loop so that you can exit the program yourself\n";
                cout<<"\n";
                break;
           default:
                    cout<<"That is not an option";
                    
                }
 
}
return 0;


}




This is the calculator I made a few years back - very simple but about as advanced as I got in C++. :)
Was This Post Helpful? 2
  • +
  • -

#17 aniri  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 54
  • View blog
  • Posts: 657
  • Joined: 24-November 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 05:53 AM

Since I've worked a lot with c++ before, but not with winapi, I decided to play a bit with it for this challenge. I wrote a feet to meters and viceversa convertor.

#include <windows.h>
#include <stdio.h>

#define IDC_CONVERT_BUTTON 101 
#define IDC_CONVERT_FEET 102 
#define IDC_CONVERT_METERS 103 


const char g_szClassName[] = "FeetToMetersConvertor";

HWND hEdit1, hEdit2, hWndButton;

LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;
        case WM_DESTROY:
            PostQuitMessage(0);
        break;
		case WM_CREATE:
		{
			hEdit1=CreateWindowEx(WS_EX_CLIENTEDGE,
				"EDIT",
				"",
				WS_CHILD|WS_VISIBLE|ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL,
				10,
				10,
				150,
				25,
				hwnd,
				(HMENU)IDC_CONVERT_FEET,
				GetModuleHandle(NULL),
				NULL);
				
			SendMessage(hEdit1,WM_SETTEXT,NULL,(LPARAM)"Feet value..."); 
			
			hEdit2=CreateWindowEx(WS_EX_CLIENTEDGE,
				"EDIT",
				"",
				WS_CHILD|WS_VISIBLE|ES_MULTILINE|ES_AUTOVSCROLL|ES_AUTOHSCROLL,
				180,
				10,
				150,
				25,
				hwnd,
				(HMENU)IDC_CONVERT_METERS,
				GetModuleHandle(NULL),
				NULL);
				
			SendMessage(hEdit2,WM_SETTEXT,NULL,(LPARAM)"Meters value..."); 
			
			hWndButton=CreateWindowEx(NULL, 
				"BUTTON",
				"Convert",
				WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_DEFPUSHBUTTON,
				10,
				40,
				100,
				25,
				hwnd,
				(HMENU)IDC_CONVERT_BUTTON,
				GetModuleHandle(NULL),
				NULL);
		}
		break;
		case WM_COMMAND:
			switch(LOWORD(wParam))
			{
				case IDC_CONVERT_BUTTON:
				{
					char* str_meters;
					int len1 = GetWindowTextLength(GetDlgItem(hwnd, IDC_CONVERT_METERS));
					str_meters = (char*)GlobalAlloc(GPTR, len1 + 1);
					GetDlgItemText(hwnd, IDC_CONVERT_METERS, str_meters, len1+1);
					double meters = atof(str_meters);
					
					char* str_feet;
					int len2 = GetWindowTextLength(GetDlgItem(hwnd, IDC_CONVERT_FEET));
					str_feet = (char*)GlobalAlloc(GPTR, len2 + 1);
					GetDlgItemText(hwnd, IDC_CONVERT_FEET, str_feet, len2+1);
					double feet = atof(str_feet);

					if (meters == 0.0 && feet == 0.0)
					{
						MessageBox(NULL, "Write a value!", "Note", MB_OK);
					}
					else if (meters == 0.0)
					{
						// convert to meters
						
						double met = feet * 0.3048;
						
						char s[20];
						sprintf(s,"%f",met);
						
						SetDlgItemText(hwnd, IDC_CONVERT_METERS, s);
					}
					else if (feet == 0.0)
					{
						// convert to feet
						
						double fee = meters * 3.2808399;
						
						char s[20];
						sprintf(s,"%f",fee);
						
						SetDlgItemText(hwnd, IDC_CONVERT_FEET, s);
					}
					else
					{
						MessageBox(NULL, "Error! Wrong values", "Note", MB_OK);
					}
				}
				break;
			}
			break;
        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    WNDCLASSEX wc;
    HWND hwnd;
    MSG Msg;

    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = g_szClassName;
    wc.hIconSm       = LoadIcon(NULL, IDI_APPLICATION);

    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    hwnd = CreateWindowEx(
        WS_EX_CLIENTEDGE,
        g_szClassName,
        "My Convertor",
        WS_OVERLAPPEDWINDOW,
        GetSystemMetrics(SM_CXSCREEN)/2-160,
		GetSystemMetrics(SM_CYSCREEN)/2-120,
		360, 120,
        NULL, NULL, hInstance, NULL);

    if(hwnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    ShowWindow(hwnd, nCmdShow);
    UpdateWindow(hwnd);

    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}


Was This Post Helpful? 2
  • +
  • -

#18 Guest_Guest*


Reputation:

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 06:55 AM

Are we trying to impress here? I've got some trigonometric functions I find very useful. When does this challenge end?


//OS Specific Includes:
#include <windows.h>

int main(int argc, char * argv[])
{
	//The most basic Windows Application:
	MessageBox(NULL,L"Hello, Windows.",L"DIC++",MB_OK);
	return 0;
}

Was This Post Helpful? 1

#19 Guest_octave*


Reputation:

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 07:02 AM

"A simple question->answer chat application" -- you mean chat application which is for LAN or Internet or it is something else ??

This post has been edited by octave: 06 April 2010 - 07:03 AM

Was This Post Helpful? 0

#20 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 965
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 07:25 AM

The following application uses the Windows API MEMORYSTATUS structure and GlobalMemoryStatus function to retrieve the total and available RAM amount installed on the Computer:
#include <iostream>
#include <windows.h>

void physical_memory_report()
{
	MEMORYSTATUS m_status;
	m_status.dwLength = sizeof(m_status);
	
	GlobalMemoryStatus(&m_status);

        // Use division with 1024*1024 to get the RAM amount in Mbytes
	DWORD RamAmount = m_status.dwTotalPhys / (1024 * 1024);

	std::cout << "Total Physical memory: " << RamAmount << " MB\n";
	std::cout << "Physical memory available: " << m_status.dwAvailPhys / (1024 * 1024) << " MB\n";
        // How much of the memory is used (the value is returned in percents):
	std::cout << "Physical memory in use (in percents): " << m_status.dwMemoryLoad << "%\n";
}

int main()
{
	physical_memory_report();

	std::cin.get();
	return 0;
}


Was This Post Helpful? 4
  • +
  • -

#21 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 09:56 AM

Thanks sarmanu, I posted this app a while back asking if I deleted all the memory I allocated:


#include <windows.h>
#include <conio.h>
#include <iostream>
#include <cstddef>

#define MAX_ARRAY 130000 
//130,000
#define ARRAY_SIZE 10000
//10,000

using namespace std;
int main()
{
	MEMORYSTATUSEX ram;
	ram.dwLength=sizeof(ram);

	GlobalMemoryStatusEx(&ram);
	cout << "The free memory is " << (ram.ullAvailPhys / (1024*1024)) << " MB" << endl;
	
	char ** mem=NULL;
	mem=new char*[MAX_ARRAY]; // trying to make a pointer to an array of pointers
	for(unsigned int i=0;i<MAX_ARRAY;i++)
	{
		mem[i]=NULL;
		mem[i]=new char[ARRAY_SIZE]; // make each pointer in the array of pointers point to a char array
	}

	/* zero it all */
	cout << "Zeroing Memory.\n";
	for(unsigned int i=0;i<MAX_ARRAY;i++)
	{
		memset(mem[i],0,ARRAY_SIZE);
	}

	/* delete memory */
	cout << "Freeing Memory..." << endl;

	for(unsigned int i=0;i<MAX_ARRAY;i++)
	{
		delete [] mem[i];
	}
	delete [] mem;
	
	//Sleep(100);
	cout << "Press any key to continue\n";
	
	_getch();
	return 0;
}


Was This Post Helpful? 2
  • +
  • -

#22 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 10:08 AM

A simple program that reminds me of middle school geometry class, and the awful goto using program I made for it.

/* Taylorc8
In case you don't notice, the functions are named like : <Category>_<triangle-problem-usage>_<returns-what>

--Note--
Trig_ASA_Length requires the angle opposite the side you want to solve for
to be an argument to the first parameter! */

#include <windows.h>


#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <sstream>

using std::cout;
using std::cin;
using std::endl;
using std::ios_base;
using std::string;
using std::stringstream;

const double dPI = 3.14159265358979; // Double PI




/*** Function Prototypes ***/

//Any three sides, returns Gamma
template < typename floatType>
floatType Trig_SSS_Gamma(floatType, floatType, floatType);

//Any three sides, returns Alpha
template < typename floatType >
floatType Trig_SSS_Alpha(floatType, floatType, floatType);

//Any three sides, returns Beta
template < typename floatType >
floatType Trig_SSS_Beta(floatType sideA, floatType sideB, floatType sideC);

//Useful when you know two sides and the angle between them:
//Two sides, and the angle between them, with the angle in Degrees!
//Returns the 3rd side
template < typename floatType >
floatType Trig_SAS_LengthC(floatType sideA,floatType angle, floatType sideB);

//Two angles, one side in the middle, angles in degrees!
// ASA returns t3h side..
template < typename floatType >
floatType Trig_ASA_Length(floatType angleA,floatType side, floatType angleB);

int main()
{
	double a, b, c;
	string choice;
	int select=0;

	while(cin)
	{
		system("cls");
		cout << "<XXX MENU XXX>" << endl;
		cout << "(1) Solving with SSS" << endl;
		cout << "(2) Solving with SAS" << endl;
		cout << "(3) Solving with ASA" << endl;
		cout << "(4) Notes.." << endl;
		cout << "#";
		cin >> choice;
		stringstream(choice) >> select;

		switch(select)
		{
		case 1:
			cout << "Enter Sides A,B,C: ";
			cin >> a >> b >> c;
			cout.precision(32); // 32 places (32 bit pc, eh?)
			cout.showpoint; // always show decimal point
			cout << "Angle Alpha is: " << Trig_SSS_Alpha(a,b,c) << endl;
			cout << "Angle Beta is: " << Trig_SSS_Beta(a,b,c) << endl;
			cout << "Angle Gamma is: " << Trig_SSS_Gamma(a,b,c) << endl;
			system("pause");
			break;
		case 2:
			cout << endl << "SAS time, Two sides and the angle between them S,A,S: ";
			cin >> a >> b >> c;
			cout << "The third side's length is: " << Trig_SAS_LengthC(a,b,c) << endl;
			system("pause");
			break;
		case 3:
			cout << "--The angle opposite the side you wish to solve for\n should come first"
				"in the input--\n";
			cout << "ASA time, A,S,A: ";
			cin >> a >> b >> c;
			cout <<"Length: " <<  Trig_ASA_Length(a,b,c) << endl;
			system("pause");
			break;
case 4:
			cout << "This doesn't help you learn unless you make it yourself." << endl;
			system("pause");
			break;
		default:
			return 0;
		}
		select=0;
		choice.clear();
	}


	return 0;
}




//SSS, returns Gamma
template < typename floatType >
floatType Trig_SSS_Gamma(floatType sideA, floatType sideB, floatType sideC)
{
	floatType gamma;

	//Determine Gamma
	gamma= (( pow(sideA,2) + pow(sideB,2) - pow(sideC,2) )) / (2*sideA*sideB);
	gamma=acos(gamma);

	//Convert to Degrees
	gamma=gamma*180/dPI;

	//return result

	return gamma;
}




//SSS, returns Alpha
template < typename floatType >
floatType Trig_SSS_Alpha(floatType sideA, floatType sideB, floatType sideC )
{
	floatType alpha;

	//Determine Alpha
	alpha = (( pow(sideB,2) + pow(sideC,2) - pow(sideA,2) )) / (2*sideB*sideC);
	alpha=acos(alpha);

	//Convert to Degrees

	alpha=alpha*180/dPI;

	return alpha;
}





//SSS, returns Beta
template < typename floatType >
floatType Trig_SSS_Beta(floatType sideA, floatType sideB, floatType sideC)
{
	floatType beta;

	//Determine Alpha
	beta = (( pow(sideA,2) + pow(sideC,2) - pow(sideB,2) )) / (2*sideA*sideC);
	beta=acos(beta);

	//Convert to Degrees
	beta=beta*180/dPI;

	return beta;
}

//Two sides, and the angle between them, with the angle in Degrees!
//returns third side.
//Ex. a, beta, c = returns length of b
template < typename floatType >
floatType Trig_SAS_LengthC(floatType sideA,floatType angle, floatType sideB)
{

	floatType sideC;

	//First, we must convert from Degrees to Radians
	angle=dPI*angle/180;

	sideC = pow(sideA,2) + pow(sideB,2) - (2*sideA*sideB) * cos(angle);


	return sqrt(sideC);
}





//Two angles, one side in the middle, angles in degrees!
//The angle opposite the side you want to solve for, should
//be in the first parameter of the function!
template < typename floatType >
floatType Trig_ASA_Length(floatType angleA,floatType side, floatType angleB)
{

	/* Law of sines applies here:
	a/sin(alpha) = b/sin(beta) = c/sin(gamma)
	*/

	floatType sideA;

	floatType angleC=180-(angleA + angleB); // get Third angle

	//First, we must convert from Degrees to Radians
	angleA=dPI*angleA/180;
	angleB=dPI*angleB/180;
	angleC=dPI*angleC/180;

	sideA = (side * sin(angleA) ) / sin(angleC);

	//Note, no value in degrees is returned, only a length.
	return sideA;

}


This post has been edited by taylorc8: 06 April 2010 - 10:08 AM

Was This Post Helpful? 1
  • +
  • -

#23 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 10:15 AM

Some WAVE sound stuff:

/*
Taylorc8 2010

Yes, we're still messing with encodings into 2010, for those interested..
This project is simple, read the RIFF header of the WAVE file (PCM)

https://ccrma.stanford.edu/courses/422/projects/WaveFormat/

*/
#define DEBUG
#include <iostream>
#include <fstream>
#include <cstring>

using namespace std;


struct RIFF_CHUNK_DESCRIPTOR
{
	char RIFF[4]; // spells out 'R I F F'
	int ChunkSize; //36 + SubChunk2Size
	char WAVE[4]; // spells 'W A V E'
};

struct FORMAT_SUB_CHUNK
{
	int SubChunk1Id;
	int SubChunk1Size;
	short AudioFormat; // 2 bytes, should equal 1 (PCM)
	short NumChannels; // 2 bytes
	int SampleRate;
	int ByteRate;
	short BlockAlign;
	short BitsPerSample;
};

struct DATA_SUB_CHUNK
{
	int SubChunk2Id;
	int SubChunk2Size;
};

/* RIFF WAVE PCM */
struct WAVE
{
	RIFF_CHUNK_DESCRIPTOR riffChunk;

	FORMAT_SUB_CHUNK formatSubChunk;

	DATA_SUB_CHUNK dataSubChunk;

	//the data follows all of these
};

/* function prototypes */
int ReadRiffHeader(WAVE &,fstream &);

template <class T>
void ReadSoundData(fstream & inFile, T * type,/*in, number of elements */ int size);

int main()
{
	WAVE soundFile;
	memset(&soundFile,0,sizeof(WAVE));
	fstream inFile("C:\\11k16bitpcm.wav",ios::in | ios::binary | ios::out);

	//populate the struct members, and display the SubChunk2Size-36
	ReadRiffHeader(soundFile,inFile);

	cout << "SubChunk2Size - 36 = " << soundFile.dataSubChunk.SubChunk2Size - 36 << endl;


	inFile.close();


	return 0;
}


int ReadRiffHeader(WAVE & soundFile,fstream& inFile)
{
	/* populate the riffChunk structure */
	inFile.read(soundFile.riffChunk.RIFF,4);
	inFile.read((char*)&soundFile.riffChunk.ChunkSize,sizeof(soundFile.riffChunk.ChunkSize));
	inFile.read(soundFile.riffChunk.WAVE,4);

	/* output info about the riffChunk struct */
#ifdef DEBUG
	cout << "Should spell RIFF: ";
	for(int i=0;i<4;i++)
		cout << soundFile.riffChunk.RIFF[i];
	cout << endl;
	cout << "Chunk Size: " << soundFile.riffChunk.ChunkSize << endl;

	cout << "Should spell WAVE: ";
	for(int i=0;i<4;i++)
		cout << soundFile.riffChunk.WAVE[i];
	cout << endl;
#endif

	/* populate the format sub chunk structure */
	inFile.read((char*) &soundFile.formatSubChunk.SubChunk1Id,sizeof(soundFile.formatSubChunk.SubChunk1Id));
	inFile.read((char*) &soundFile.formatSubChunk.SubChunk1Size,sizeof(soundFile.formatSubChunk.SubChunk1Size));
	inFile.read((char*) &soundFile.formatSubChunk.AudioFormat,sizeof(soundFile.formatSubChunk.AudioFormat)); // 2 bytes
	inFile.read((char*) &soundFile.formatSubChunk.NumChannels,sizeof(soundFile.formatSubChunk.NumChannels));// 2 bytes
	inFile.read((char*) &soundFile.formatSubChunk.SampleRate,sizeof(soundFile.formatSubChunk.SampleRate));
	inFile.read((char*) &soundFile.formatSubChunk.ByteRate,sizeof(soundFile.formatSubChunk.ByteRate));
	inFile.read((char*) &soundFile.formatSubChunk.BlockAlign,sizeof(soundFile.formatSubChunk.BlockAlign)); // 2 bytes
	inFile.read((char*) &soundFile.formatSubChunk.BitsPerSample,sizeof(soundFile.formatSubChunk.BitsPerSample)); // 2 bytes

	/* output info about the formatSubChunk struct */
#ifdef DEBUG
	cout << "SubChunk1Id: " << soundFile.formatSubChunk.SubChunk1Id << endl;
	cout << "SubChunk1Size: " << soundFile.formatSubChunk.SubChunk1Size << endl;
	cout << "Audio Format (should equal 1 for PCM): " << soundFile.formatSubChunk.AudioFormat << endl;
	cout << "Number of channels: " << soundFile.formatSubChunk.NumChannels << endl;
	cout << "Sample Rate: " << soundFile.formatSubChunk.SampleRate << endl;
	cout << "Byte Rate: " << soundFile.formatSubChunk.ByteRate << endl;
	cout << "Block Align: " << soundFile.formatSubChunk.BlockAlign << endl;
	cout << "Bits Per Sample: " << soundFile.formatSubChunk.BitsPerSample << endl;
#endif

	/* populate the dataSubChunk structure */
	inFile.read((char*) &soundFile.dataSubChunk.SubChunk2Id,sizeof(soundFile.dataSubChunk.SubChunk2Id));
	inFile.read((char*) &soundFile.dataSubChunk.SubChunk2Size,sizeof(soundFile.dataSubChunk.SubChunk2Size));

	/* output info about the dataSubChunk struct */
#ifdef DEBUG
	cout << "DataSubChunk2Id: " << soundFile.dataSubChunk.SubChunk2Id << endl;
	cout << "DataSubChunk2Size: " << soundFile.dataSubChunk.SubChunk2Size << endl;
#endif

	return 0;
}




/* 
Precondition: get pointer is at the Sound Data section!
Postcondition: get pointer is left at the end of what was read.

ReadSoundData, this function accepts a pointer to an array of the proper type for each sample. 
The second parameter is the number of elements in the array, NOT THE NUMBER OF BYTES IN IT*/
template <class T>
void ReadSoundData(fstream & inFile, T * type, /*in, number of elements */ int size)
{
	inFile.read((char*)&type,size*sizeof(*type));
}



This post has been edited by taylorc8: 06 April 2010 - 10:16 AM

Was This Post Helpful? 1
  • +
  • -

#24 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 10:24 AM

And not to spam the forum with everything on my hard drive, a Windows API Tick Timer class, behold:

"Timer.h"
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#ifndef TIMER_H
#define TIMER_H

#include <windows.h>

class Timer
{
public:
	Timer(int hours,int minutes); //specify how long to wait
	Timer(); // init total minute time to zero
	bool CheckTime(); //returns true on time equal to, or time passed the wait
	void SetTime(int hours, int minutes); // specify how long to wait
private:
	LARGE_INTEGER frequency;
	LARGE_INTEGER tickCount;
	LARGE_INTEGER time;   // For converting tick into real time
	long long totalMinuteCount;
	long long minuteCountAtSet;
};

#endif




"Timer.cpp"
#include "Timer.h"

Timer::Timer()
{
	totalMinuteCount=0;

	//Number of ticks per second
	QueryPerformanceFrequency(&frequency);

	QueryPerformanceCounter(&tickCount); // Number of ticks

	time.QuadPart=tickCount.QuadPart/frequency.QuadPart; // seconds..
	minuteCountAtSet=time.QuadPart/60; // minutes
}
Timer::Timer(int hours,int minutes)
{
	totalMinuteCount=(hours*60)+minutes;
	
	//Number of ticks per second
	QueryPerformanceFrequency(&frequency);

	QueryPerformanceCounter(&tickCount); // Number of ticks

	time.QuadPart=tickCount.QuadPart/frequency.QuadPart; // seconds..
	minuteCountAtSet=time.QuadPart/60; // minutes
}

bool Timer::CheckTime()
{
	//Number of ticks per second
	if(!QueryPerformanceFrequency(&frequency))
		return false;

	QueryPerformanceCounter(&tickCount); // Number of ticks

	time.QuadPart=tickCount.QuadPart/frequency.QuadPart; // seconds..
	time.QuadPart/=60; // minutes

	if(time.QuadPart>=(totalMinuteCount+minuteCountAtSet))
		return true;
	else
		return false;
}

void Timer::SetTime(int hours, int minutes)
{
	totalMinuteCount=(hours*60)+minutes;
	//Number of ticks per second
	QueryPerformanceFrequency(&frequency);

	QueryPerformanceCounter(&tickCount); // Number of ticks

	time.QuadPart=tickCount.QuadPart/frequency.QuadPart; // seconds..
	minuteCountAtSet=time.QuadPart/60; // minutes
}


Was This Post Helpful? 1
  • +
  • -

#25 Core  Icon User is offline

  • using System.Linq;
  • member icon

Reputation: 773
  • View blog
  • Posts: 5,097
  • Joined: 08-December 08

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 11:48 AM

View Postoctave, on 06 April 2010 - 03:02 PM, said:

"A simple question->answer chat application" -- you mean chat application which is for LAN or Internet or it is something else ??


If you have experience to develop a LAN chat application in C++, then this is great. If not - it could be an app that lets the user "talk" with the computer.
Was This Post Helpful? 0
  • +
  • -

#26 SwiftStriker00  Icon User is offline

  • Microsoft Insider
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,596
  • Joined: 25-December 08

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 01:34 PM

This is a little command line interface that utilizes task scheduler to create popup reminders. Theres some reason Windows wont let you run it on SYSTEM user, so I had to prompt for current username and password. Its a little buggy but i'll see if i have time to fix it.

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <fstream>
#include <Windows.h>
#include <stdio.h>
#include <cstdlib>
#include <conio.h>
#include "ConsoleColor.h"
using namespace std;


std::string getPass()
{
    char tempChar;
    std::string passIn = "";

    tempChar = getch();
    while (tempChar != char(13)) {
      std::cout << "*";
      passIn += tempChar;
      tempChar = getch();
    }

    std::cout << "\n";
    return passIn;
}//getPass():string

int main(int argc, char *argv[])
{
    //System Variables
    int NEW = 1, EXIT = 0, option = 1;
    string input = "";
    char * defaultColors = "color 08"; 
    bool repeater = false,easterEgg = false;
    ostringstream stm;
    
    SYSTEMTIME st;
    GetSystemTime(&st);
    
    int yr = st.wYear,
        mo = st.wMonth,
        day = st.wDay,
        hour = st.wHour,
        min = st.wMinute,
        sec = st.wSecond;
    
    string scheduleType = "ONCE";
    string modifier = "1";
    string days = "MON";
    string months = "*";

    string message = "Alarm Message!";
    string title = "Alarm Title";
    string user = "System", pass = ""; 
    
    //Begin UI
    
    cout << "Welcome to Task Creator v1.1.2 || By Ryan Bucinell" << endl;
    cout << "--------------------------------------------------" << endl;    
    cout << green << "New Feature: Password Confirmation. To help garentee success" <<endl;
    cout << yellow << "Next version will support repeating tasks after implementation change." << white <<endl;
    cout << yr << ", " << mo << ", " << day << ", " << hour << ", " << min << ", " << sec << endl;
    
    while( option != EXIT ){
           //Main Menu
           cout << "---------\nEnter # of desired option" << endl;
           cout << "1. New Task" << endl;
           cout << "0. Exit\n>";
           cin >> input;
           option = atoi( input.substr(0,1).c_str() );
           cout << endl;
           if( option == NEW ){
               //Date
               cout << "---------\nWhat date will this task go off?" << endl;
               cout << "(use format MMDDYYYY, or 0 for today)\n> ";
               cin >> input;
               input = input.substr(0,8); //Garentee Propper Size
               if( input.substr(0,1) != "0" ){
                   mo = atoi( input.substr(0,2).c_str() );
                   day = atoi( input.substr(2,2).c_str() );
                   yr = atoi( input.substr(4,4).c_str() );     
               }
               system("cls");
               //Time
               cout << "---------\nAt what time? (Defualt 15:00:00pm)" << endl;
               cout << "(use format HHMMSS or 0 for defualt (24hour input style)\n> ";
               cin >> input;
               input = input.substr(0,6);
               if( input.substr( 0,1) == "0" ){
                   hour = 15;
                   min = 00;
                   sec = 00;
               }else{
                   hour = atoi( input.substr(0,2).c_str() );
                   min  = atoi( input.substr(2,2).c_str() );
                   sec = atoi( input.substr(4,2).c_str() );
               }
               system("cls");
               //Insert Repetition Code Here
               
               //End Repetition Code
               
               //Message
               cout << "---------\nWhat is the message you would like to show?\n> ";
               getline(cin,input); //dunno, made it work
               getline( cin, input );
               message = input;
               //Title
               title = "Alarm_";
               ( hour < 10 ) ? stm << 0 << hour : stm << hour;
               ( min < 10 ) ? stm << 0 << min : stm << min;
               ( sec < 10 ) ? stm << 0 << sec : stm << sec;
               title.append( stm.str() );
               stm.clear();
               cout << "---------\nWhat is the title of the reminder? 0 for default (Default: " << title << ")\n> ";
               getline( cin, input);
               if( input.substr( 0,1) != "0" ){
                   title = input;
               }
               cout << endl;
               system("cls");
               
               //Verification of Security
               user = "";
               user.append( getenv("username") );
               cout << "---------\nPermisions needed to run tasks on your computer!\n Please enter your windows user or 0 

for default\n(Default: " +user+")> ";
               getline( cin, input );
               if( input != "" && input.substr(0,1) != "0" ){
                   user = input;
               }
               bool passEq = false;
               string pass1, pass2;
               while( !passEq ){
                      cout << "Password:\n> ";
                      pass1 = getPass();
                      cout << "Confirm Password:\n> ";
                      pass2 = getPass();
                      passEq = (pass1 == pass2) ? true : false; 
                      if( !passEq ) {
                          cout << red << "Passwords did not match! " << white << endl;
                      }else{
                            pass = pass1;
                      } 
               }
               //Setup Time
               ostringstream stmD, stmT;
               string date, time;
               ( hour < 10 ) ? stmT << 0 << hour : stmT << hour;
               stmT << ":";
               ( min < 10 ) ? stmT << 0 << min : stmT << min;
               stmT << ":";
               ( sec < 10 ) ? stmT << 0 << sec : stmT << sec;
               time.append( stmT.str() );
               stmT.clear();
               //Setup Date
               ( mo < 10 ) ? stmD << 0 << mo : stmD << mo;
               stmD << "/";
               ( day < 10 ) ? stmD << 0 << day : stmD << day;
               stmD << "/" << yr;
               date.append( stmD.str() );
               stmD.clear();
               //Setup Task
               string theTask = "schtasks /create";
               ostringstream stmTT;
               stmTT << " /tn \"" << title << "\"";
               stmTT << " /tr \"%WINDIR%\\system_reminders\\" << title << ".bat\"";
               stmTT << " /st " << time << "";
               stmTT << " /sd " << date << "";
               stmTT << " /sc " << scheduleType;
               //If Repeater Code Here
               
               //End Repeater Code
               stmTT << " /ru " << user;
               stmTT << " /rp " << pass;
               stmTT << " >nul";
               theTask.append( stmTT.str() );
               
               //Create Batch file with reminder
               fstream fileWriter;
               string batchTitle = title + ".bat";
               fileWriter.open(batchTitle.c_str(), ios::out);
               // write a line of text to the file
               fileWriter << "@echo off" <<endl;
               fileWriter << "echo " <<endl;
               fileWriter << "title " << title <<endl;
               fileWriter << "echo." <<endl;
               fileWriter << "echo " << message <<endl;
               fileWriter << "echo." <<endl;
               fileWriter << "pause" <<endl;
               fileWriter << "del %WINDIR%\\Tasks\\" << title << ".job" <<endl;
               fileWriter << "start /min cmd /c del /q %~s0" <<endl;
               fileWriter << "goto :eof" <<endl;
               fileWriter.close();  
               
               //Create File to Generate Task
               fileWriter.open(("setup.bat"), ios::out);
                // write a line of text to the file
               fileWriter << "@echo off" <<endl;
               fileWriter << "title setup" <<endl;
               fileWriter << "mkdir \"%WINDIR%\\system_reminders\"" <<endl;
               fileWriter << "xcopy " << title << ".bat \"%WINDIR%\\system_reminders\" /Q /R /Y >nul" <<endl;
               fileWriter << theTask <<endl;
               fileWriter << "del " << title << ".bat" <<endl;
               fileWriter << "start /min cmd /c del /q %~s0" <<endl;
               fileWriter << "goto :eof" <<endl;
               fileWriter.close();   
               
               system("setup.bat");
               system("cls");
               cout << green << "Success!" << white << endl;  
               
               stm.flush(); 
               stmTT.flush(); 
               stmT.flush(); 
               stmD.flush();
           }
                     
    }
    cout << "Goodbye!" <<endl;
    return EXIT_SUCCESS;
}



heres the console color class i used but didnt write:
// ConsoleColor.h


#pragma once
#include <iostream>

#include <windows.h>


inline std::ostream& blue(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout, FOREGROUND_BLUE
              |FOREGROUND_GREEN|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& red(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout,
                FOREGROUND_RED|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& green(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout,
              FOREGROUND_GREEN|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& yellow(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout,
         FOREGROUND_GREEN|FOREGROUND_RED|FOREGROUND_INTENSITY);
    return s;
}

inline std::ostream& white(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout,
       FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    return s;
}

inline std::ostream& black(std::ostream &s)
{
    HANDLE hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout,
       FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_BLUE);
    return s;
}

struct color {
    color(WORD attribute):m_color(attribute){};
    WORD m_color;
};

template <class _Elem, class _Traits>
std::basic_ostream<_Elem,_Traits>&
      operator<<(std::basic_ostream<_Elem,_Traits>& i, color& c)
{
    HANDLE hStdout=GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hStdout,c.m_color);
    return i;
}

// Copyleft Vincent Godin


This post has been edited by SwiftStriker00: 06 April 2010 - 01:36 PM

Was This Post Helpful? 1
  • +
  • -

#27 sarmanu  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 965
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 01:59 PM

An integer class, mainly demonstrating operator overloading:
#include <iostream>
#include <string>

class Int
{
	friend std::ostream &operator<<(std::ostream &os, const Int &i);
	friend std::istream &operator>>(std::istream &is, Int &i);
private:
	int number;
public:
        // More things could be added, but the purpose is learning
	Int();
	Int(const long long int number);
	Int(const Int &i);
	
	const bool operator==(const Int &i) const;
	const bool operator<(const Int &i) const;
	const bool operator<=(const Int &i) const;
	const bool operator>(const Int &i) const;
	const bool operator>=(const Int &i) const;
	const bool operator!=(const Int &i) const;

	Int &operator+=(const Int &i);
	const Int operator+(const Int &i) const;

	Int &operator-=(const Int &i);
	const Int operator-(const Int &i) const;

	Int &operator*=(const Int &i);
	const Int operator*(const Int &i) const;

	Int &operator/=(const Int &i);
	const Int operator/(const Int &i) const; 

	Int &operator%=(const Int &i);
	const Int operator%(const Int &i) const;

	Int &operator++();
	Int operator++(int);

	Int &operator--();
	Int operator--(int);
};

Int::Int()
{
	number = 0;
}

Int::Int(const long long int number)
{
	if (number > INT_MAX || number < -INT_MAX)
		throw std::string("Invalid integer!");

	this->number = static_cast<int>(number);
}

Int::Int(const Int &i)
{
	number = i.number;
}

std::ostream &operator<<(std::ostream &os, const Int &i)
{
	os << i.number;
	return os;
}

std::istream &operator>>(std::istream &is, Int &i)
{
	is >> i.number;
	return is;
}

const bool Int::operator==(const Int &i) const
{
	return (number == i.number);
}

const bool Int::operator<(const Int &i) const
{
	return (number < i.number);
}

const bool Int::operator<=(const Int &i) const
{
	return (number <= i.number);
}

const bool Int::operator>(const Int &i) const
{
	return (number > i.number);
}

const bool Int::operator>=(const Int &i) const
{
	return (number >= i.number);
}

const bool Int::operator!=(const Int &i) const
{
	return !(*this == i);
}

Int &Int::operator+=(const Int &i)
{
	number = number + i.number;

	return *this;
}

const Int Int::operator+(const Int &i) const
{
	Int temp = *this;
	temp += i;
	return temp;
}

Int &Int::operator-=(const Int &i)
{
	number = number - i.number;

	return *this;
}

const Int Int::operator-(const Int &i) const
{
	Int temp = *this;
	temp -= i;
	return temp;
}

Int &Int::operator*=(const Int &i)
{
	number = number * i.number;

	return *this;
}

const Int Int::operator*(const Int &i) const
{
	Int temp = *this;
	temp *= i;
	return temp;
}

Int &Int::operator/=(const Int &i)
{
	number = number / i.number;

	return *this;
}

const Int Int::operator/(const Int &i) const
{
	Int temp = *this;
	temp /= i;
	return temp;
}

Int &Int::operator%=(const Int &i)
{
	number = number % i.number;

	return *this;
}

const Int Int::operator%(const Int &i) const
{
	Int temp = *this;
	temp %= i;
	return temp;
}

Int &Int::operator++()
{
	number = number + 1;
	return *this;
}

Int Int::operator++(int)
{
	Int temp = *this;
	++(*this);
	return temp;
}

Int &Int::operator--()
{
	number = number - 1;
	return *this;
}

Int Int::operator--(int)
{
	Int temp = *this;
	--(*this);
	return temp;
}

int main()
{
	// Mostly equivalent with "int c", but "Int" default constructor
	// initializes "c" with 0
	Int c; // Declare an "integer", and initializes it with 0
	std::cout << c << std::endl; 

	// Demonstrates operator >>
	std::cout << "Enter a number: ";
	std::cin >> c;
	std::cout << "Entered: " << c << std::endl;

	// Operations:
	Int d(c); // copy-constructor
	std::cout << d << std::endl;

	d++; // operator ++
	std::cout << d << std::endl;
	d--; // operator --
	std::cout << d << std::endl;

	d *= 2; // operator *=
	std::cout << d << std::endl;

	d /= 2; // operator /=
	std::cout << d << std::endl;

	// more operators at once:
	std::cout << d + 1 + (c / 2) - (d * 2) * (d % 3) << std::endl;

	Int f = 22, D = 22;
	if (f == D)
		std::cout << "Equal numbers!" << std::endl;
	else
		std::cout << "Not equal!" << std::endl;

	// You can use every operators that "int" type uses: <, <=, >, >=, !=

	// You can use the class as loop counters:
	for (Int i = 0; i < 10; i++)
		std::cout << i << " ";

	// Etc ...
	std::cin.ignore();
	std::cin.get();
	return 0;
}


Was This Post Helpful? 1
  • +
  • -

#28 taylorc8  Icon User is offline

  • B&

Reputation: 149
  • View blog
  • Posts: 1,572
  • Joined: 21-July 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 03:30 PM

One last submission, last one, I promise.

A class to find the title of the current foreground window, and optionally terminate the process associated with it,
It uses the Windows API to do it. Quite a fun little class, especially for those pesky internet explorer windows.

WindowTextKill.h
/* This class will grab the title of the current foreground window, and compare it with a substring
the programmer inputs.
Also, you can optionally terminate the running process of the current foreground window after matching the text
*/

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#ifndef WINDOWTEXTKILL_H
#define WINDOWTEXTKILL_H

#include <windows.h>
#include <cstdio>
#include <iostream>
#include <psapi.h>

/*
The GetText member: 0 on success 1 on error
*/

struct Window
	{
	DWORD pid;
	HWND hwnd; // handle to window
	char text[512]; // used to store window text
	char substr[512]; // fill this baby out, and it's ready to for action
	HANDLE processHandle;	
};


class WindowTextKill
{
private:	
	Window window;

public:
	WindowTextKill()
	{}

	//Insert substring into Window struct for comparison
	WindowTextKill(char * substring)
	{
		strcpy_s(window.substr,512,substring);
	}

	~WindowTextKill()
	{}

	/* If the substring is found in the foreground window's title, it will attempt to
	terminate the process.  The GetText member will allow you to simply retrieve the 
	foreground window's text. */
	bool Kill();


	//Insert substring into Window struct for comparison with the window's title
	int SetString(char* sstring);


	//Grab the foreground window's text and put it in textbuffer up to length
	bool GetText(char *textbuffer,int length);

};



#endif




WindowTextKill.cpp

#include "WindowTextKill.h"

// To kill a running process, if the title matches the substring
// you were searching for
bool WindowTextKill::Kill()
{
	window.hwnd=GetForegroundWindow();
	if(window.hwnd==NULL)
		return false;

	GetWindowTextA(window.hwnd,window.text,512);
	if( strstr(window.text,window.substr) != NULL )
	{
		GetWindowThreadProcessId(window.hwnd,&window.pid);
		window.processHandle=OpenProcess(PROCESS_TERMINATE,true,window.pid);
		TerminateProcess(window.processHandle,0);
		CloseHandle(window.processHandle);
	}
	return true;
}



//Insert substring into Window struct for comparison with the window's title
int WindowTextKill::SetString(char* sstring)
{
	if(sstring==NULL)
	{
		return 1;
	}
	else
	{
		strcpy_s(window.substr,512,sstring);
		return 0;
	}
}



//Grab the foreground window's text and put it in textbuffer up to length
bool WindowTextKill::GetText(/* out */ char *textbuffer,int length)
{
	if(length>0 && (textbuffer != NULL) )
	{
		window.hwnd=GetForegroundWindow();
		GetWindowTextA(window.hwnd,textbuffer,(int)length);
		return FALSE;
	}
	else
		return TRUE;
}

Was This Post Helpful? 1
  • +
  • -

#29 programble  Icon User is offline

  • (cons :dic :head)

Reputation: 49
  • View blog
  • Posts: 1,315
  • Joined: 21-February 09

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 05:06 PM

This is my palindrome checker:
/* Palindrome checker
 * Written by Programble
 * Licensed under the WTFPL
 */

#include <iostream>
#include <string>

using namespace std;

int main(int argc, char **argv)
{
    cout << "Programble's Palindrome Checker" << endl;
    cout << "Enter \"exit\" to exit" << endl;
    while (true)
    {
        string input = "";
        cout << "Enter a word: ";
        cin >> input;
        if (input == "exit")
        {
            break;
        }
        string reversed = "";
        for (int i = input.length() - 1; i >= 0; i--)
        {
            reversed += input[i];
        }
        if (reversed == input)
        {
            cout << "Word is a palindrome";
        }
        else
        {
            cout << "Word is not a palindrome";
        }
        cout << endl;
    }
    return 0;
}


Was This Post Helpful? 1
  • +
  • -

#30 smeezekitty  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 18-December 08

Re: Week #14 Challenge: C++

Posted 06 April 2010 - 07:24 PM

Well its not written specifically for this but you can check out my OS at http://smeeze.homelinux.com
Was This Post Helpful? 0
  • +
  • -

  • (5 Pages)
  • +
  • 1
  • 2
  • 3
  • 4
  • Last »