The Student Room Group

C++ practice programs

So I'm teaching myself C++, and I decided to make a little imitation drink vending machine program to put some of the basics I've learned into practice.

Does anyone know anywhere that gives you example programs you can try writing yourself? Or perhaps could you give me some examples of programs you have wrote yourself whilst learning the language, which i could try and write myself (just a description of what the program should do would be nice, rather than source code i can copy :P).

Source code for the vending machine program is below (should give you an idea of the level I'm up to (very basic :P)
If you notice any improvements i could make to the program to increase functionality or make it more efficient please let me know.
The vending machine is designed to be run or "turned on" once, and will then repeat the main menu to choose a drink until the machine is set to out of order in the system menu or "turned off" (close the window).

Ta :smile:

Note: ugh, the indentation looks terrible when using the code tags. But you get the idea.

#include <iostream>
#include <string>
using namespace std;


//Money Variables
float price;
float getmoney;
float change;
//Choice Variables
int choice;
int systemchoice;
//Drink Variables
int cocacola;
int dietcocacola;
int drpepper;
int mountaindew;
//Other Variables
int run;
string password;
string getpassword;

void TurnedOn()
{
cout <<"This machine has just been switched on!" <<endl;
cout <<"Please do some basic set up..." <<endl;
cout <<"\n";
system("PAUSE");
system("cls");
while (password.size() <4){
cout <<"Please enter the system password:" <<endl;
cout <<"(Password must be at least 4 characters)" <<endl;
cin >>password;
}
cout <<"Please enter the standard price of drinks:" <<endl;
cin >>price;
system("cls");
cout <<"Please enter the current amount of stock for:" <<endl;
cout <<"Coca Cola:";
cin >>cocacola;
system("cls");
cout <<"Please enter the current amount of stock for:" <<endl;
cout <<"Diet Coca Cola:";
cin >>dietcocacola;
system("cls");
cout <<"Please enter the current amount of stock for:" <<endl;
cout <<"Dr Pepper:";
cin >>drpepper;
system("cls");
cout <<"Please enter the current amount of stock for:" <<endl;
cout <<"Mountain Dew:";
cin >>mountaindew;
system("cls");
}


void VendCoke()
{
cout <<"Please insert $" <<price <<endl;;
cin >>getmoney;
change = (getmoney - price);
cocacola = (cocacola - 1);
cout << "\nYour change is: $" <<change <<endl;
system("pause");
system("cls");
}

void VendDietCoke()
{
cout <<"Please insert $" <<price <<endl;
cin >>getmoney;
change = (getmoney - price);
dietcocacola = (dietcocacola - 1);
cout << "\nYour change is: $" <<change <<endl;
system("pause");
system("cls");
}

void VendDrPepper()
{
cout <<"Please insert $" <<price <<endl;
cin >>getmoney;
change = (getmoney - price);
drpepper = (drpepper - 1);
cout << "\nYour change is: $" <<change <<endl;
system("pause");
system("cls");
}

void VendMountainDew()
{
cout <<"Please insert $" <<price <<endl;;
cin >>getmoney;
change = (getmoney - price);
mountaindew = (mountaindew - 1);
cout << "\nYour change is: $" <<change <<endl;
system("pause");
system("cls");
}

void SystemMenu()
{
system("cls");
cout <<"*****************************************" <<endl;
cout <<"*****************************************" <<endl;
cout <<"** System Menu **" <<endl;
cout <<"** **" <<endl;
cout <<"**1. Check Stock Levels **" <<endl;
cout <<"**2. Refill Stock **" <<endl;
cout <<"**3. Change Prices **" <<endl;
cout <<"**4. Set Machine Out Of Order **" <<endl;
cout <<"**5. Change System Password **" <<endl;
cout <<"*****************************************" <<endl;
cout <<"*****************************************" <<endl;

cin >>systemchoice;
if (systemchoice == 1){
system("cls");
cout <<"*****************************************" <<endl;
cout <<"*****************************************" <<endl;
cout <<"** Stock Levels **" <<endl;
cout <<"** **" <<endl;
cout <<"**1. Coca Cola: " <<cocacola <<" **" <<endl;
cout <<"**2. Diet Coca Cola: " <<dietcocacola <<" **" <<endl;
cout <<"**3. Dr Pepper: " <<drpepper <<" **" <<endl;
cout <<"**4. Mountain Dew: " <<mountaindew <<" **" <<endl;
cout <<"*****************************************" <<endl;
cout <<"*****************************************" <<endl;
cout <<"\n";
system("PAUSE");
}
if (systemchoice == 2){
cout <<"Please enter the current amount of stock for: Coca Cola" <<endl;
cin >>cocacola;
system("cls");
cout <<"Please enter the current amount of stock for: Diet Coca Cola" <<endl;
cin >>dietcocacola;
system("cls");
cout <<"Please enter the current amount of stock for: Dr Pepper" <<endl;
cin >>drpepper;
system("cls");
cout <<"Please enter the current amount of stock for: Mountain Dew" <<endl;
cin >>mountaindew;
system("cls");
}
if (systemchoice == 3){
cout <<"Please enter the new drinks price:" <<endl;
cin >>price;
system("cls");
}
if (systemchoice == 4){
run=0;
}
if (systemchoice == 5){
system("cls");
cout <<"Please enter the new system password:" <<endl;
cin >>password;
while (password.size() <4){
cout <<"Please enter the system password:" <<endl;
cout <<"(Password must be at least 4 characters)" <<endl;
cin >>password;
}
}

}


void MainMenu()
{
system("cls");
cout <<"*****************************************" <<endl;
cout <<"*****************************************" <<endl;
cout <<"**Choose an option by entering a number**" <<endl;
cout <<"** All drinks are currently $" <<price <<" **" <<endl;
cout <<"** **" <<endl;
cout <<"**1. Coca Cola **" <<endl;
cout <<"**2. Diet Coca Cola **" <<endl;
cout <<"**3. Dr Pepper **" <<endl;
cout <<"**4. Mountain Dew **" <<endl;
cout <<"** **" <<endl;
cout <<"**0. System Menu **" <<endl;
cout <<"*****************************************" <<endl;
cout <<"*****************************************" <<endl;

cin >> choice;
if (choice == 1) {
VendCoke();
}
if (choice == 2) {
VendDietCoke();
}
if (choice == 3) {
VendDrPepper();
}
if (choice == 4) {
VendMountainDew();
}
if (choice == 0) {
cout <<"Please enter the system password:" <<endl;
cin >>getpassword;
if (getpassword == password){
SystemMenu();
getpassword == "";
}
}
}

int main()
{
run = 1;
TurnedOn();
while(run != 0)
{
MainMenu();
}
system("cls");
cout <<"This machine is out of order. Sorry!" <<endl;
cout <<"\n" <<endl;
cout <<"\n" <<endl;
system("PAUSE");

return 0;
}
Reply 1
i am so upset now after reading this:frown:
Reply 2
Mark266
i am so upset now after reading this:frown:


What have I done? :frown:
Reply 3
Avoid global variables, avoid using system(), use a switch statement when possible instead of lots of if statements, avoid "using namespace std".

Other than that keep up the practise(loads of beginners start off doing the stuff above which is frowned upon). Ill post a few practise program ideas in a minute.
Reply 4
Okay, thanks :smile:
What would you suggest instead of global variables when i need them in different parts of the program? Or do you mean it would be better to assign them in main?

The book I've been reading said to use "using namespace std", is it not needed?

Ah yeah just looked up switch statements in my book, hadn't got that far yet :P

What's another way of pausing the program to allow users to read the output rather than system("PAUSE")? And clearing the screen too rather than system("cls")?

Also, just curious, why is system() and namespace frowned upon?
Reply 5

What would you suggest instead of global variables when i need them in different parts of the program? Or do you mean it would be better to assign them in main?

You can pass them as function parametres. Try keep your functions small and as self sufficient as possible.


The book I've been reading said to use "using namespace std", is it not needed?
The problem with it is that it includes the entire namespace when your only using smalls parts of it. I wouldn't worry about it till you've had more practise.


What's another way of pausing the program to allow users to read the output rather than system("PAUSE")

cin.get();


why is system() frowned upon?

Its not operating system independant, if you ran the program on an OS like Linux it may not have the pause command.

system("cls")
Sorry don't know of a better way to clear the screen :rolleyes:

Program 1 (was a task first semester at uni)
Change machine - User buys an item with e.g. £20 then machine displays the change in appropate coinage. e.g. 1*£2 1*50p 1*20p

Program 2(Palindrome finder)
Takes a word as input then tells you if its a palindrome.
Defenition:a word or words that read the same in both directions. Example: LEVEL,MADAM

Program 3High score bored.
Takes 10 scores as input then displays them in order highest to lowest.

That should keep you busy.
Reply 6
Thanks very much, I'll get to work!
Reply 7
Only cross platform ways I could think of clearing the screen off hand would be to use #ifndef to figure out what platform you're compiling for (and then call cls or clear), or to use another library like ncurses. :/
The real question is - do you really need to clear the screen? It's actually quite an annoying thing for a program to do.
Also note that cin.get() has its own problems for pausing the program on completion (specifically, if there's anything left in the input buffer - not uncommon - then it's likely to appear to simply be skipped). To avoid this, you need something more like:

std::cin.ignore(std::cin.rdbuf()->in_avail());
std::cin.get();


IMHO: Either use system("pause") and don't bother pretending it's anything other than a hideous, non-portable, security-hole ridden hack, or learn to use [the command line|your IDE] to run the program as it's intended. The latter option being much preferable. YMMV.
Reply 10
I think your vending machine program is a good start, so well done, but it could certainly do with some improvement ;-).

I'm not going to rewrite the whole thing for you, but I have written something similar using a slightly more elegant technique for you. I'd suggest going back to your vending machine program and trying to fix it up in a similar way.

I've tried my best to keep it extremely simple, but chances are there might be some stuff in there that you don't understand. If so, don't hesitate to ask.

This is still not a perfect implementation, but hopefully I'm not teaching you too many bad habits in my quest to keep it simple :-)




#include <iostream>
#include <string>

class Vendable
{
public:
//Constructor
Vendable( unsigned int stock, std::string name )
{
// Normally I'd use initialisers here, but I'm trying to keep it
// simple ( See http://www.devx.com/tips/Tip/33146 )
stock_ = stock;
name_ = name;
}

//Destructor
~Vendable()
{
}

unsigned int getStock() const
{
return stock_;
}

std::string getName() const
{
return name_;
}

// If this returns false then cannot vend!
bool vend()
{
if ( stock_ )
{
--stock_;
return true;
}

// Out of stock!
return false;

}

private:

// Data Members
unsigned int stock_;
std::string name_;
};


void stockLevels( Vendable** vendables, unsigned int num_vendables )
{
std::cout << "Stock Levels:" << std::endl;

for ( unsigned int i = 0; i < num_vendables; ++i )
{
std::cout << vendables[ i ]->getName() << " : " << vendables[ i ]->getStock() << std::endl;
}

std::cout << std::endl;
}



void buy( Vendable* v )
{
if ( v->vend() )
{
std::cout << "Vended a " << v->getName() << std::endl;
}
else
{
std::cout << "COULD NOT VEND! OUT OF STOCK OF " << v->getName() << std::endl;
}

std::cout << std::endl;
}



int main()
{
const unsigned int starting_stock = 10;
const unsigned int num_vendables = 4;

Vendable* vendables[ num_vendables ];

vendables[ 0 ] = new Vendable( starting_stock, "Coca Cola" );
vendables[ 1 ] = new Vendable( starting_stock, "Diet Coke" );
vendables[ 2 ] = new Vendable( starting_stock, "Dr Pepper" );
vendables[ 3 ] = new Vendable( starting_stock, "Mountain Dew" );


stockLevels( vendables, num_vendables );

buy( vendables[ 0 ] );
buy( vendables[ 1 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 2 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 3 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 3 ] );
buy( vendables[ 3 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );
buy( vendables[ 0 ] );


stockLevels( vendables, num_vendables );

delete vendables[ 0 ];
delete vendables[ 1 ];
delete vendables[ 2 ];
delete vendables[ 3 ];

return 0;
}

Reply 11
Small scale games are always fun to program. I wrote one to play mastermind (the user had to guess the code, I couldn't make an algorithm to make the computer do it anything more than randomly), and I'm doing one to play hangman now. You can make them as complicated or as simple as you like, depending on how functional and how good at the game they will be, and they tend not to require a vast programming knowledge - hangman is mostly arrays with for loops iterating over them. Sometimes it has an if statement :biggrin:.

Another favourite, I believe, is to write programs, as you have done, to emulate everyday machines, such as bank machines, vending machines, ovens... Anything you can see!

Also, if you're mathematically oriented, search for project Euler on Google. But seriously, only if you're VERY mathematically oriented :wink:

Latest

Trending

Trending