an array of more than one data type

Hey everyone this is my first post here, I am a beginner in c++.
I was solving the tasks I found on this website here:
http://www.cplusplus.com/forum/articles/12974/
While I was doing the "cola machine" I wanted to do it "nightmare mode" and try to use all the things I I know about C++ till now.
User sees the beverages available.
Inserts money.
The Drinks that he can afford appear.
User enters the number of the drink he wants.
Drink is printed, the remaining money is returned if available.
It is very similar except the drinks have prices to relate to, how can I let the same drinks(array) contain a string and a char? Here is the code, which might help you understand better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include "stdafx.h"
#include <iostream>
#include<string>
using namespace std;

void main()
{
	int i;
	double money;
	string drinks[5];
	drinks[0]="Club Soda";//$0.50
	drinks[1]="7-Up";//$.75
	drinks[2]="Miranda";//$.75
	drinks[3]="Pepsi";//$.75
	drinks[4]="Ice Tea";//$1.00

	cout<<"Please check out our available drinkserages"<<endl;
	for (i=0;i<5;i++)
	{
		cout<<i+1<<". "<<drinks[i]<<endl;
	}
	cout<<"________________________________________________________________________________"<<endl;
	cout<<"Please insert any ammount of money in cents. "<<endl;
	cin>>money;
	cout<<"$"<<money/100;
	
Learn about structs.
You could separate the different parts by some delimiter:

drinks[0] = "Club Soda:0.50";

Then you find where the ':' is within the string. Everything from the start, up to but not including the ':' is the drink name. Everything after ':' is the price.

This may be more work than using a struct or class though, but it will give you good exposure to string work.
Last edited on
@peter87
i know a little about structs, but i don't know how to apply what i learned about it till now.
@roberts
how can i use that if i want to cout the pre-':', or compare whats after the ';' with an int?
excuse my noobiness :)
Copy to another string.

string drinkname = drink.substr(0, drink.find(':', 0));
string price = drink.substr(drink.find(':', 0 ) + 1, 4);

then convert price to an float. You can't use decimals in integer data types unless you start working with fixed-point or BCD, then again, you're back to more work than is necessary.


A struct is simply:

1
2
3
4
5
struct Drink
{
     string name;
     float   price;
};


Then:

Drink drink[5] = { "Club soda", 0.50f, "7-up", 0.75, "Miranda", 0.75, ...};

Then loop through the list.
Last edited on
@roberts:
thanks mate i will try using a struct, i will have to learn it later anyways :).
Topic archived. No new replies allowed.