9 Replies - 446 Views - Last Post: 12 May 2013 - 06:52 AM Rate Topic: -----

#1 sharky7337  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 09-May 13

Help!

Posted 09 May 2013 - 10:41 PM

Im writing a project and its for a car lot and im creating classes. I need to fullfill certain requirements. For accessory descriptions I need to use a pointer to a string that can be used to dynamically allocate an array of strings with the exact number of accessories. Each element will hold the name of the accessory.

If the number of accessories is 0, there is no need to allocate space, set the pointer to null.

And also pointer to a double that can eb used to dynamically allocate an array of doubles with the same number of elements as accessories. Each element will hold the cost of the associated accessory, that is, the cost in element 0 is the cost of the accessory in element 0.
If the number of accessories is zero, set the pointer to null since there is no need to allocate space.

Heres what my class is so far without those last two requirements. Im stumped.

#ifndef VEHICLE_H
#define VEHICLE_H


class Vehicle
{
    public:
        Vehicle();
    protected:
        int vin_number;
        string manufacturer;
        string model;
        string color;
        double basecost;
        int accessories;
        string accessory_list;
        char[]
    private:
};

#endif // VEHICLE_H



Please help it's an online course and ive been googling and reading for hours. :/

Is This A Good Question/Topic? 0
  • +

Replies To: Help!

#2 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: Help!

Posted 09 May 2013 - 11:33 PM

You need to use a pointer to a string

so this
string accessory_list;



should be this
string *accessory_list;



You can then point the accessory_list pointer to an array of strings. I suggest you do some research on pointers and dynamic memory allocation (new operator)
Was This Post Helpful? 0
  • +
  • -

#3 sharky7337  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 09-May 13

Re: Help!

Posted 09 May 2013 - 11:54 PM

Thanks YA i know the new operator takes memory from the heap and uses it until deleted. I know how to make pointers and stuff my biggest issue is how would i write the function to do that? When should i delete the variables?

View Postsharky7337, on 09 May 2013 - 11:51 PM, said:

Thanks YA i know the new operator takes memory from the heap and uses it until deleted. I know how to make pointers and stuff my biggest issue is how would i write the function to do that? When should i delete the variables?

#ifndef VEHICLE_H
#define VEHICLE_H


class Vehicle
{
    public:
        Vehicle();
    protected:
        int vin_number;
        string manufacturer;
        string model;
        string color;
        double basecost;
        int accessories;
        string* accessory_list;
        double* cost_list;
    private:
};



Here is the updated version but whow would the method look to dynamically allocate an array of strings eith the exact number of accessories.
Was This Post Helpful? 0
  • +
  • -

#4 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: Help!

Posted 10 May 2013 - 12:42 AM

Most of the time, memory is dynamically allocated in the constructor of a object (but not always). Try doing some research on constructors and deconstructors.
Was This Post Helpful? 0
  • +
  • -

#5 jimblumberg  Icon User is offline

  • member icon


Reputation: 4013
  • View blog
  • Posts: 12,384
  • Joined: 25-December 09

Re: Help!

Posted 10 May 2013 - 07:04 AM

Also consider std::vector instead of the array with dynamic memory. This is really what the vector class was designed for in the first place.

Jim
Was This Post Helpful? 1
  • +
  • -

#6 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: Help!

Posted 11 May 2013 - 02:16 AM

View Postjimblumberg, on 10 May 2013 - 10:04 AM, said:

Also consider std::vector instead of the array with dynamic memory. This is really what the vector class was designed for in the first place.

Jim


As Jim has suggested, is there really any point to 're-invent the wheel' ?

( Here ... just use the vector container class ... to do your work ...
Learning how to code a vector container ... that's best left for a separate project! )

So ... using the STL vector to DO your work for you ...

here's a (start to a) way to do it ...

( If you really have to code your own vector class ...
then do that separately ...
test it out to make sure it works well ...
then just use that class in place of the STL vector here. ...
THAT WAY, you keep FINDING coding errors separate for the two distinct jobs. )


This example demos a way to take in ...

some vehicles ...

into a STL vector container (from the user via keyboard input) ...

then when done the input loop ...

displays that info back to the console screen.


(Note! it uses a separate .h file to hold the class Vehicle code, which file code follows the test program)

// test program and utility functions ...
// to takeIn info from keyboard
// and to then display it back to console when done

// test_classVehicle.cpp  // 2013-05-11 //


// A start to a vehicle data base to help track info on all your vehicles ... //


#include <iostream>
#include <iomanip>
#include <sstream> // re. stringstream obj's

#include <string>
#include <vector>

#include <cctype> // re. tolower
#include <limits>

#include "classVehicle.h"

//using namespace std;

template< typename T >
T takeInValue( const std::string& msg, const T& min, const std::string& errMsg )
{
    T val;
    while( true )
    {
        std::cout << msg << std::flush;
        if( std::cin >> val && std::cin.get() == '\n' && val >= min )
            break;
        else
        {
            std::cout << errMsg;
            std::cin.clear();
            std::cin.sync();
        }
    }
    return val;
}

// returns a non-empty string with CAPS on ALL first letters ...
std::string takeInValue( const std::string& msg )
{
    std::string val;
    for( ; ; )
    {
        std::cout << msg << std::flush;
        getline( std::cin, val );
        size_t len = val.size();
        if( len )
        {
            val[0] = toupper( val[0] );
            size_t pos = 0;
            while( len && ( pos = val.find( ' ', pos )) != std::string::npos )
            {
                ++pos;
                len = val.size() - pos;

                val[pos] = toupper( val[pos] );
            }
            break;
        }
        // else ...
        std::cout << "\nBlank line not valid here ...\n";
    }

    return val;
}

char getCharReply( const std::string& msg )
{
    std::cout << msg << std::flush;
    std::string reply;
    getline( std::cin, reply );
    if( reply.size() ) return reply[0];
    // else ...
    return 0;
}

void takeInAccessories( std::vector < Accessories > & vacc )
{
    int counter = 0;
    do
    {
        // form takeIn message ...
        std::ostringstream oss;
        oss << std::setw(2) << ++counter << ". Enter accessory ";

        std::string name = takeInValue( oss.str() + "name: " );

        double cost = takeInValue< double >
                    ( oss.str() + "cost: ", 0,
                      "\nOnly 'float type' numbers here please ...  " );

        vacc.push_back( Accessories( name, cost ));
    }
    while( tolower( getCharReply( "\nMore accessories "
                                  "(defaults to 'y': y/n) ? " )) != 'n' );
}

double showAccessories( const std::vector < Accessories > & vacc )
{
    int size = vacc.size();
    double sumExtras = 0;
    for( int i = 0 ; i < size ; ++i )
    {
        double cost = vacc[i].get_cost();
        sumExtras += cost;
        std::cout << "Add " << std::setw(2) << i+1 << " "
                  << std::setw(23) << vacc[i].get_name()
                  << " "
                  << std::setprecision(2) << std::showpoint << std::fixed
                  << std::setfill( '.' ) << std::setw(47) << cost
                  << std::setfill( ' ' ) << std::endl;
    }
    return sumExtras;
}

void showVehicle( const Vehicle& vhcl )
{
    double tot = vhcl.get_basecost();
    std::cout << std::setw(10) << vhcl.get_vin()
              << std::setw(20) << vhcl.get_manufacturer()
              << std::setw(16) << vhcl.get_model()
              << std::setw(16) << vhcl.get_color()
              << std::setprecision(2) << std::showpoint << std::fixed
              << std::setw(16) << tot << std::endl;
    if( vhcl.get_extras().size() )
    {
       tot += showAccessories( vhcl.get_extras() );
       std::cout << std::setw(78) << "========" << "\n"
                 << std::setw(78) << tot << std::endl;
    }
}

void showAllVehicles( const std::vector< Vehicle >& myCars )
{
    int size = myCars.size();
    for( int i = 0; i < size; ++ i )
    {
        showVehicle( myCars[i] );
        std::cout << std::endl;
    }
}

void showHeader()
{
    std::cout << std::setw(10) << "VIN"
              << std::setw(20) << "MANUFACTURER"
              << std::setw(16) << "MODEL"
              << std::setw(16) << "COLOR"
              << std::setw(16) << "BASECOST" << std::endl;
}

bool vinFound( const std::vector< Vehicle >& vhcl, int vin )
{
    int size = vhcl.size();
    for( int i = 0; i < size; ++ i )
        if( vhcl[i].get_vin() == vin )
        {
            std::cout << "\n" << vin << " was already used ...\n";
            return true;
        }
    // else ...
    return false;
}

bool takeInVehicle( std::vector< Vehicle >& v )
{
    Vehicle vhcl; // get empty Vehicle ...

    // form err message ...
    std::ostringstream oss;
    oss << "\nPositive integers less than "
        << std::numeric_limits< int >::max()<< " only please.\n";

    int vin;
    for( ; ; )
    {
        vin = takeInValue< int >( "Enter vin: ", 0, oss.str() );
        if( !vinFound( v, vin ) ) break;
    }

    vhcl.set_vin( vin );
    vhcl.set_manufacturer( takeInValue( "Enter manufacturer: " ));
    vhcl.set_model( takeInValue( "Enter model: " ));
    vhcl.set_color( takeInValue( "Enter color: " ));
    vhcl.set_basecost( takeInValue< double >
                  ( "Enter basecost: ", 0,
                    "\nOnly 'float type' numbers here please ...  " ));

    if( tolower( getCharReply( "Accessories (defaults to 'n': y/n) ? " ))
        == 'y' )
    {
        std::vector< Accessories > vacc;
        takeInAccessories( vacc );
        vhcl.set_extras( vacc );
    }

    showHeader();
    showVehicle( vhcl );

    if( tolower( getCharReply( "Ok to accept (y/n) ? " )) == 'y' )
    {
        v.push_back( vhcl );
        return true;
    }
    // else ...
    return false;
}



int main()
{
    std::vector< Vehicle > myCars; // get empty vector

    do
    {
        if( !takeInVehicle( myCars ))
            std::cout << "\nRecord was NOT enetered ... \n";
    }
    while( tolower( getCharReply( "\nMore vehicles "
                                  "(defaults to 'y': y/n) ? " )) != 'n' );

    std::cout << "\nYou entered: \n";
    showHeader();
    showAllVehicles( myCars );

    return 0;
}




// call this file ...

// classVehicle.h //  // 2013-05-11 //

#ifndef VEHICLE_H
#define VEHICLE_H

#include <string>
#include <vector>

class Accessories
{

public:
    // ctor (with default and passed in values ...
    Accessories( const std::string& nam ="", double cst =0 )
                 : name(nam), cost(cst) {} // initialization list ...
    // getters ...
    std::string get_name() const { return name; }
    double get_cost() const { return cost; }

private:
    std::string name;
    double cost;
} ;


class Vehicle
{

public:
    // default ctor ...
    Vehicle() : vin(0), basecost(0) {}

    // setters ...
    void set_vin( int svin ) {  vin = svin; }
    void set_manufacturer(  const std::string& sman ) { manufacturer = sman ; }
    void set_model( const std::string& smod ) {  model = smod; }
    void set_color( const std::string& scol  ) { color = scol; }
    void set_basecost( double sbas ) { basecost = sbas; }

    void set_extras( const std::vector< Accessories >& sext ) { extras = sext; }

    // getters ...
    int get_vin() const { return vin; }
    std::string get_manufacturer() const { return manufacturer; }
    std::string get_model() const {  return model; }
    std::string get_color() const { return color; }
    double get_basecost() const { return basecost; }

    const std::vector< Accessories >& get_extras() const { return extras; }

private:
    int vin;
    std::string manufacturer;
    std::string model;
    std::string color;
    double basecost;

    // also tracks number of accesories via size
    std::vector< Accessories > extras;

} ;

#endif


Was This Post Helpful? 0
  • +
  • -

#7 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1072
  • View blog
  • Posts: 4,532
  • Joined: 09-June 09

Re: Help!

Posted 11 May 2013 - 02:44 AM

The requirement states that they need to use a pointer to a dynamic array, do you really think it would be acceptable to use a vector? Yes, they may be "re inventing the wheel", but I'm sure the assignment was assigned to learn about dynamic memory, not pre-canned containers.

This post has been edited by jjl: 11 May 2013 - 02:45 AM

Was This Post Helpful? 0
  • +
  • -

#8 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: Help!

Posted 11 May 2013 - 03:19 AM

View Postjjl, on 11 May 2013 - 05:44 AM, said:

The requirement states that they need to use a pointer to a dynamic array, do you really think it would be acceptable to use a vector? Yes, they may be "re inventing the wheel", but I'm sure the assignment was assigned to learn about dynamic memory, not pre-canned containers.


Please do not quote me out of context ... or maybe you missed this context:

Quote

( If you really have to code your own vector class ...
then do that separately ...
test it out to make sure it works well ...
then just use that class in place of the STL vector here. ...
THAT WAY, you keep FINDING coding errors separate for the two distinct jobs. )

This post has been edited by David W: 11 May 2013 - 03:20 AM

Was This Post Helpful? 0
  • +
  • -

#9 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 3548
  • View blog
  • Posts: 10,986
  • Joined: 05-May 12

Re: Help!

Posted 11 May 2013 - 09:48 PM

I don't know, he could have a vector of pointers to objects... He would still be using dynamic memory for the object, but not necessarily a dynamically allocated array.
Was This Post Helpful? 0
  • +
  • -

#10 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: Help!

Posted 12 May 2013 - 06:52 AM

View PostSkydiver, on 12 May 2013 - 12:48 AM, said:

I don't know, he could have a vector of pointers to objects... He would still be using dynamic memory for the object, but not necessarily a dynamically allocated array.


Good point :)

The OP, will need to point to (or copy here)
the exact original design spec's
to see what was actually required.

As is sometimes the case,
the original design spec's,
and
'a student's paraphrase'
can be somewhat different.

This post has been edited by David W: 12 May 2013 - 07:02 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1