1

Hey I have a pretty simple question to be answered. I assigned elements of my array to string values. I want my code to output the string instead of the element value. Here is an example:

double stock[5] = {249.99,49.99,13.99,449.99,59.99}; double Beats = stock[0]; double iPod = stock[1]; std::cout << "Okay, you purchased " << stock[0] << endl;

The output I would like is "Okay, you purchased Beats." . The output I recieve is "Okay, you purchased 249.99."

How can I make it print the string instead of the value? Thank you in advance.

flyer3110
  • 35
  • 5

3 Answers3

3

You'll likely want some kind of container, be it a struct, class or pair. Here's an example (using a pair):

#include <utility>
#include <string>

...

std::pair <std::string,double> stock [5];
stock[0]=std::make_pair("Beats",249.99);

...

std::cout << "Okay, you purchased " << stock[0].first << "." << endl;

This will output what you want ("Okay, you purchased Beats.").

You can use stock[i].first to access the first element (the name, as a string), and stock[i].second to access the second element (the value, as a double).

wilcroft
  • 1,580
  • 2
  • 14
  • 20
1
string items[5] = {"Beats", "iPod", "CD", "Vinyl", "Sheet"};
std::cout << "Okay, you purchased " << items[0] << endl;

If you want to maintain the numbers (i.e stock) also, you need something a little more sophisticated.

Beta
  • 96,650
  • 16
  • 149
  • 150
-1

I assume you need to display what item has been purchased and at what price. If so, may be you need something like following.

#include <iostream>
using namespace std;

struct item_struct
{
    std::string item;
    double price;
    item_struct(string _item, double _price)
    {
        item = _item;
        price = _price;
    }
};

int main() {

    item_struct *stock[5] = {new item_struct("Beats", 249.99),
                                new item_struct("iPod", 49.99),
                                new item_struct("CD", 13.99),
                                new item_struct("iPone", 899.99),
                                new item_struct("Nexus 5", 499.99)
                                };

    std::cout << "Okay, you purchased " << stock[0]->item << endl;

    std::cout << "Okay, you purchased " << stock[3]->item
                << " at the price of " << stock[3]->price
                << endl;

    return 0;
}

Result:

Okay, you purchased Beats
Okay, you purchased iPone at the price of 899.99
Ankit Patel
  • 1,191
  • 1
  • 9
  • 9