David W 131 Practically a Posting Shark

Firstly ...
please note that if you wish your code to be portable,
do not use <conio.h>

You can use a C struct and a typedef to create whatever data record you need.

typedef struct
{
    char* name;
    int id;
    int scores[5];

} Student;

And then in your main function ... get space to hold as many records as you need:

Student studs[100]; /* reserve space to hold 100 Student rec's */
campuzcrazyness commented: Thanks. +1
David W 131 Practically a Posting Shark

...1) when I use the displayStudentNames function, the names are being printed in reverse order from what I put in,

Because you are using a 'push_front' with each new student you add.
You could easily use a 'push_back' instead
(and keep a pointer to the 'back' so you can easily add the next student after the 'back'.)

2) graduation dates aren't being printed out, so I'm not sure if they're being stored correctly, if at all, 3) when I use the displayStudentInfo function, it either works incorrectly, or crashes the program.

You are not re-setting the 'top' pointer at the start of each new loop query

If you really must store C strings in your stuct ...
see this edit that uses C++ strings to ease your take in of strings ...
(You can easily store the data there as a C string ... And it's easy to chop off any char's that exceed the max length that you wish to store.)

// Student.cpp //

#include <iostream>
#include <cstring>
#include <string> // to handle input of string of any size //

using namespace std;


const int NAME_SIZE = 49;

struct Student
{
   char name[NAME_SIZE+1];
   int age;
   double gpa;
   char gradSemesterAndYear[4];
   Student *next;
};


void displayStudentNames( const Student* top );
void displayStudentInfo( const Student* top );



int main()
{
    string line;
    Student *top = 0;

    cout << "You will be prompted to enter: \n"
         << "name, \n"
         << "age, \n"
         << "gpa, …
David W 131 Practically a Posting Shark

Can you code a C ++ shell program to get started?

Can you code to take in data in a loop?

If not ... look here:

http://developers-heaven.net/forum/index.php/topic,2019.0.html

David W 131 Practically a Posting Shark

Why are you using C strings in a C++ program ? (Way better to use C++ string, most of the time.)

David W 131 Practically a Posting Shark

P.S.
If you lookup direct addressing vs. indirect addressing ...
that too may help you understand more about pointers.

If you also lookup
read-only memory vs. read and write memory
that too should shed some light on what the compiler is doing.

Your question, perhaps, could be re-expresed like this:
what is the correct C/C++ syntax to say a value is held constant (after it is first created)
and ...
what is the correct C/C++ syntax to say an address is held constant (after it is first created)

David W 131 Practically a Posting Shark

A pointer is simply a variable that holds an address.

// compiler told val is a label to access this int '10' it puts into memory somewhere //
int val = 10; 

cout << "val = " << val << endl; //compiler knows val is an int and block address in memory//

// p is a label to access the address of some int
// compiler informed that p is to hold address of an int //
int* p = &val; // p now holds the address of val //

cout << "*p = " << *p << " and p = " << p << endl;

If you compile and run the above simple example ... it may help.

Note that every variable name is an alias (a label ... a handle) to some address ... thus you can take the address of a pointer variable and so have a pointer to a pointer

int** pp = & p;
David W 131 Practically a Posting Shark

Another oops ... found in code above. Please edit/update as per code below ...

    Stack& operator = ( const Stack& stk ) // overlooaded operator =
    {
        if( this != &stk )
        {
            //len = 0;
            //end = start = 0;
            clear(); // to prevent memory leak //
            if( stk.len )
            {
                Element* cur = stk.start;
                end = start = new Element( cur->key );
                ++len;
                cur = cur->next;
                while( cur )
                {
                    Element* new_pe = new Element( cur->key );
                    end->next = new_pe;
                    end = new_pe;
                    ++len;
                    cur = cur->next;
                }
            }
        }
        return *this;
    }
David W 131 Practically a Posting Shark

Can your Stack class have,
beside the usual ...
push (front)
pop (front)
front
back ...

can it also have iterators ...
Iter it;
++ it method and it ++ method
Iter begin() method
Iter end() method
and methods with calls like ...
erase( it_previous, it )
get_key_at( it )
?

If so ... the quick sort could be a function
(a function that calls another function)
that is not part of the Stack class.

If that is that what you need ...
please supply ALL the original spec's so that we can see UPFRONT
all the limitations assigned ....
and so that there are NO more bunny trails.

David W 131 Practically a Posting Shark

Oops ...

There was a bug in the above code.

Please use the version below ...

and also see the added debug / compile option switches

and corrected comments

and more descriptive variable names.

// test_stack_with_quick_sort_fixed.cpp //

#include <iostream>
#include <fstream>
#include <climits> // re. INT_MIN //


using namespace std;

#define addInOpts 1   // set to 0 to turn off, set to 1 to turn on //

#define qsortDebug 1  // set to 0 to turn off, set to 1 to turn on //



const char* FNAME = "keys.txt";

/*
4 3 2 1 0 9 8 7 6 5
*/

class Stack;
// Note the forward declaration  ...
// so can give Stack 'friend class status' in class Element
// and thus to give the Stack class 
// free access to the private parts of class Element. //


class Element
{
public:
    Element( int key=0, Element* next=0 ) : key(key), next(next) {}
private:
    int key;
    Element* next;
    friend class Stack;
} ;



class Stack
{
private:
    Element* start;
    Element* end;
    int len;
public:
    Stack() : start(0), end(0), len(0) {} // default ctor...
    ~Stack() { clear(); }

    Stack( const Stack& stk ) // copy ctor...
    {
        len = 0;
        end = start = 0;
        if( stk.len )
        {
            Element* cur = stk.start;
            end = start = new Element( cur->key );
            ++len;
            cur = cur->next;

            while( cur )
            {
                Element* new_pe = new Element( cur->key );
                end->next = new_pe;
                end = new_pe;
                ++len;
                cur = cur->next;
            }
        }
    }

    Stack& operator …
David W 131 Practically a Posting Shark

Recalling ...

... did not at all attempt to implement your 'state diagram'

The following code (that uses a typedef) is more compact and thus easier to follow:

// Chameleon3.cpp //

#include <iostream>
#include <string>

using namespace std;

enum ChameleonState { COLD, WARM, ANGRY, ENRAPTURED };
const string STATES[] = { "COLD", "WARM", "ANGRY", "ENRAPTURE" };


enum TempState { low, high };
const string TEMPS[] = { "<50 ", ">=50 " };

enum ColourState { brown, yellow, green, red };
const string COLOURS[] = { "brown", "yellow", "green", "red" };



class Chameleon
{
public:
    // default ctor... //
    Chameleon() : moodState(COLD), colourState(brown), tempState(low) {}

    void display()
    {
        cout << string( 24, '*' ) << "\n\n";
        cout << " State is " << STATES[moodState] << endl;
        cout << " Color is " << COLOURS[colourState] << endl;
        cout << " Temperature is " << TEMPS[tempState] << "\n\n";
    }
    void processEvent( int event )
    {
        (this->*fns[event]) ();
        display();
    }

private:
    void TempLess()
    {
        colourState = brown;
        tempState = low;
    }
    void TempMore()
    {
        colourState = green;
        tempState = high;
    }
    void Predator()
    {
        moodState = ANGRY;
        tempState= high;
        colourState = red;
    }
    void NoPredator()
    {
        moodState = WARM;
        tempState = high;
    }
    void Mate()
    {
        colourState = yellow;
        moodState = ENRAPTURED;
        tempState = high;
    }
    void NoMate()
    {
        moodState = COLD;
        tempState = low;
        colourState = yellow;
    }

    ChameleonState moodState;
    ColourState colourState;
    TempState tempState;

    typedef void (Chameleon::*Func) ();
    static const Func fns[6];
} ;


const Chameleon::Func Chameleon::fns[6] =
{
    &Chameleon::TempLess, &Chameleon::TempMore, …
David W 131 Practically a Posting Shark

OK ... try this ...
See source credit for the (original C version of) quick sort in the program comments ...

// test_stack_with_quick_sort.cpp //

#include <iostream>
#include <fstream>
#include <climits> // re. INT_MIN //


using namespace std;


const char* FNAME = "keys.txt";

/*
4 3 2 1 0 9 8 7 6 5
*/


struct Element
{
    int key;
    Element* next;

    Element( int key=0, Element* next=0 ) : key(key), next(next) {}
} ;



struct Stack
{
    Element* start;
    Element* end;
    int len;

    Stack() : start(0), end(0), len(0) {} // default ctor...
    ~Stack() { clear(); }

    Stack( const Stack& stk ) // copy ctor...
    {
        len = 0;
        end = start = 0;
        if( stk.len )
        {
            Element* cur = stk.start;
            end = start = new Element( cur->key );
            ++len;
            cur = cur->next;

            while( cur )
            {
                Element* new_pe = new Element( cur->key );
                end->next = new_pe;
                end = new_pe;
                ++len;
                cur = cur->next;
            }
        }
    }

    Stack& operator = ( const Stack& stk ) // overlooaded operator =
    {
        if( this != &stk )
        {
            len = 0;
            end = start = 0;
            if( stk.len )
            {
                Element* cur = stk.start;
                end = start = new Element( cur->key );
                ++len;
                cur = cur->next;

                while( cur )
                {
                    Element* new_pe = new Element( cur->key );
                    end->next = new_pe;
                    end = new_pe;
                    ++len;
                    cur = cur->next;
                }
            }
        }
        return *this;
    }

    void push_front( int key )
    {
        Element* new_pe = new Element( key );
        if( len )
        {
            new_pe->next = …
David W 131 Practically a Posting Shark

I think you firstly need to get more info to be able to understand the question.

The question (part 3 below) is poorly worded!

input :
1)it is an array of n integers depecting number of seats won by the party one in each state
2)it is an array of n integers depecting number of seats won by the party two in each state
3)An integers containing number of integers N

Does 3) mean to ...
firstly input the number of states into a variable called N (before inputting anything else) ?

If that is the case, you could use dynamic arrays of integers, each of size N, (or better to use vector< int > containers) to hold the number of seats won per state (index 0..(N-1)) in the N sized array (or vector) for each of the two competing parties.

David W 131 Practically a Posting Shark

This also seems to handle your problem ok ...

// Chameleon2.cpp //

#include <iostream>
#include <string>

using namespace std;

enum ChameleonState { COLD, WARM, ANGRY, ENRAPTURED };
const string STATES[] = { "COLD", "WARM", "ANGRY", "ENRAPTURE" };


enum TempState { low, high };
const string TEMPS[] = { "<50 ", ">=50 " };

enum ColourState { brown, yellow, green, red };
const string COLOURS[] = { "brown", "yellow", "green", "red" };

const int tempLess = 1, tempMore = 2;
const int predator = 3, noPredator = 4;
const int mate = 5,     noMate = 6;


class Chameleon
{
public:
    // default ctor... //
    Chameleon() : moodState(COLD), colourState(brown), tempState(low)
    {
        eventArr[tempLess] = &Chameleon::TempLess;
        eventArr[tempMore] = &Chameleon::TempMore;
        eventArr[predator] = &Chameleon::Predator;
        eventArr[noPredator] = &Chameleon::NoPredator;
        eventArr[mate] = &Chameleon::Mate;
        eventArr[noMate] = &Chameleon::NoMate;
    }

    void display()
    {
        cout << string( 24, '*' ) << "\n\n";
        cout << " State is " << STATES[moodState] << endl;
        cout << " Color is " << COLOURS[colourState] << endl;
        cout << " Temperature is " << TEMPS[tempState] << "\n\n";
    }
    void processEvent(int event)
    {
        (this->*eventArr[event]) ();
        display();
    }

private:
    void TempLess()
    {
        colourState = brown;
        tempState = low;
    }
    void TempMore()
    {
        colourState = green;
        tempState = high;
    }
    void Predator()
    {
        moodState = ANGRY;
        tempState= high;
        colourState = red;
    }
    void NoPredator()
    {
        moodState = WARM;
        tempState = high;
    }
    void Mate()
    {
        colourState = yellow;
        moodState = ENRAPTURED;
        tempState = high;
    }
    void NoMate()
    {
        moodState = COLD;
        tempState = low;
        colourState = yellow;
    }


    ChameleonState moodState;
    ColourState …
David W 131 Practically a Posting Shark

Ok I finally had time to look at your code ...

You stated:

... I just need help in understanding why it's not changing ...

So ... the code below may help you to see ... 'why it's not changing' ...
(I did not at all attempt to implement your 'state diagram'.)

// Assignment10.cpp //

#include <iostream>
#include <string>

using namespace std;

enum ChameleonState { COLD, WARM, ANGRY, ENRAPTURED };
const string STATES[] = { "COLD", "WARM", "ANGRY", "ENRAPTURE" };


enum TempState { low, high };
const string TEMPS[] = { "<50 ", ">=50 " };

enum ColourState { brown, yellow, green, red };
const string COLOURS[] = { "brown", "yellow", "green", "red" };

const int tempLess = 1, tempMore = 2;
const int predator = 3, noPredator = 4;
const int mate = 5,     noMate = 6;


class Chameleon
{
public:
    // default ctor ...
    Chameleon() : moodState(COLD), colourState(brown), tempState(low)
    {
        eventArr[tempLess] = &TempLess;
        eventArr[tempMore] = &TempMore;
        eventArr[predator] = &Predator;
        eventArr[noPredator] = &NoPredator;
        eventArr[mate] = &Mate;
        eventArr[noMate] = &NoMate;
    }

    void display()
    {
        cout << string( 24, '*' ) << "\n\n";
        cout << " State is " << STATES[moodState] << endl;
        cout << " Color is " << COLOURS[colourState] << endl;
        cout << " Temperature is " << TEMPS[tempState] << "\n\n";
    }
    void processEvent(int event)
    {
        (this->*eventArr[event]) ();
        display();
    }

private:
    void TempLess()
    {
        colourState = brown;
        tempState = low;
    }
    void TempMore()
    {
        colourState = green;
        tempState = high;
    }
    void Predator()
    {
        moodState = …
David W 131 Practically a Posting Shark

Here is a link to an other quick sort example that you might like to see ...
(I tried the pseudo-code suggested by Dani's @Invisal ... but this looks even more interesting ... as it has optimizations to output list's that are already sorted ... or ... already reverse sorted ... in O(n) time.

http://stackoverflow.com/questions/14805936/optimal-quicksort-for-single-linked-list

David W 131 Practically a Posting Shark

Thanks ... (sorry I missed seeing the link) ... I'll take a look and get back as soon as I can.

David W 131 Practically a Posting Shark

Could you provide the full original spec's for your problem?

I supect you are missing something there ...

But in any case,
in order to begin to help you effectively,
one really needs full disclosure of what was expected ...
(by the spec's to which you were instructed to comply.)

David W 131 Practically a Posting Shark

... how to write a function that sort elements in two dynamic stacks (contained in an external file) by the quicksort method?

So ... it seems your problem really boils down to this:

Read in a supplied file containing several integers ...
(say it is called: " Integers1.txt")
into some (user designed - like a dynamic array?) container
and quicksort those integers.

Then output those sorted int's into a file called: "SortedIntegers1.txt".

Do this for a 2nd supplied file ...
(say it is called: "Integers2.txt")

That fact that, here, it was the contents of a stack that was dumped into a file does NOT really have any bearing on sorting those numbers.

David W 131 Practically a Posting Shark

Then do not use a linked list structure for your stack ...

Instead ...use a dynamic array, with a push_back and a pop_back ...
as the basis for your stack ...

But why do you wish to sort a stack ???

David W 131 Practically a Posting Shark

... Examine the state diagram and then write a C++ program that models the diagram.

The diagram ?

David W 131 Practically a Posting Shark

What you have here is really some code for the start to single-link linked list.
I do not think a quick-sort type sort is practical on a single-link linked list ... a merge sort makes more sense

David W 131 Practically a Posting Shark

... would still like some more precise direction so I might understand it better the next time.

Then ... it would help if you could supply the complete program spec's ... and code.

David W 131 Practically a Posting Shark

I would re-design ... bottom up and use table lookups and not use pointers at all.

Also, you seem to have redundant data ... for example ... temperature and temperature string ... but only need to store the temperature ...and then can lookup the other when needed.

David W 131 Practically a Posting Shark

You could use some functions ... maybe something like this to start:

from turtle import *
from math import *

speed(5)

def rectangle( x, y, w, h ):
    up()
    goto( x, y )
    setheading(0)
    down()
    for repeat in range( 2 ):
        fd(w)
        left(90)
        fd(h)
        left(90)

def peak( x, y, w, h ):
    up()
    goto( x, y )
    down()
    goto(x+w/2, y+h)
    goto( x+w, y )

#HOUSE
rectangle( 100, 0, 200, 100 )
peak( 100, 100, 200, 60 )


def tree( x, y, w, h ):
    up()
    goto( x, y+h )
    down()
    setheading( -45 )
    for repeat in range(3):
        fd( .9*h/4/cos(45) )
        rt(180-45)
        fd( w/3 )
        left( 180-45 )
    up()
    goto( x, y+h )
    down()
    setheading( (45+180) )
    for repeat in range(3):
        fd( .9*h/4/cos(45) )
        left(180-45)
        fd( w/3 )
        right( 180-45 )
    setheading(0)
    fd(.9*w)
    rectangle(x-w/20, y, w/10, h/10 )

tree( -50, 0, 100, 160 )
tree( -250, 0, 100, 160 )
tree( -250, -200, 100, 140 )
tree( -50, -200, 80, 120 )
David W 131 Practically a Posting Shark

This may help you to get started ...

David W 131 Practically a Posting Shark
#include<iostream>
#include<conio.h> // don't use to keep code portable
#include<string.h> // use <cstring>
#include<iomanip>
#include<iostream>
#include<fstream>
#include<Windows.h> // don't use to keep code portable
using namespace std; // don't use to avoid 'name clashes as code grows in size //

// and use ... .h and .cpp clas files and compile as a project //
// use C++ string every where to accomodate any string length 
// and change your file writes and reads to match //
David W 131 Practically a Posting Shark

Ok ... It looks like you want to do something like the following ...
(... and it seems also that you do not need to store input lines in an array ... so ... no array needed ...)

open input file as fin
open output file as fout

if fin and fout ok
    While still a next data line in input file 
        read data on line from input file 
        process data in line
        write processed data to output file 

Or more C++ like:

open input file as fin
open output file as fout

if fin and fout ok
     While next data line reads in ok  
        process data in line
        write processed data to output file 

Is this what you wish to do ?

Try to code in the C++ code ... using the ideas above ... and see what you can do and show us what you have ... if you get stuck?

P.S.
Things you will want to get clear in your mind before you start ...
* Does you data file always begin with an int (integer) value, that indicates how many line follow?
* Is there a blank (empty file) line immediately after that int?
* Do all the data records have their own line ... and each line ends with " E" (singlespaceE) character sequence?
* Are all names single names i.e. WITHOUT spaces in the name?
* Is there always 6 numbers after the name and …

David W 131 Practically a Posting Shark

Nice little problem you posted ... there are many ways to code a solution.

Some nice and neat way would be best with clear logic flow.

Probably using a C++ struct ( or class ) would help quite a bit.

Please show us what code you have tried so far.

Then we can see where you are 'stuck' and how to best get you 'un-stuck'.

Also provide a copy of the data file you are using.

If you know about using C++ struct ... here is an hint to a start:

struct Agent
{
    string name;
    vector< int > sales; // dollars in a month //
} ;

And ...
if you know about using stringstream objects ...
hint hint ...
use them here to ease your coding.

David W 131 Practically a Posting Shark

I would re-think what you are trying to do?

This example of a 'class Cube' may give you some ideas re. a simpler design.

example of a test main file:

// cube_test.cpp //


#include "cube.h"


int main()
{
    Cube cu( Point(0, 0, 0), 1 );
    cu.show();

    printf( "Press 'Enter' to continue/exit ... " ); fflush( stdout );
    getchar();
}

.h file:

// cube.h //

#ifndef CUBE_H
#define CUBE_H

#include <cstdio>

struct Point
{
    int x, y, z;

    Point( int x=0, int y=0, int z=0 ) : x(x), y(y), z(z) {}

    void print() const
    {
        printf( "(%d, %d, %d)\n", x, y, z );
    }
} ;


class Cube
{
public:
    Cube( const Point& pt, int cwidth );
    void show() const;
private:
    int width;
    Point corner[2][2][2];
} ;

#endif;

.cpp file:

// cube.cpp //

#include "Cube.h"


Cube::Cube( const Point& pt, int cwidth ) : width(cwidth)
{ 
    for( int ix = 0; ix < 2; ++ix )
    {
        for( int iy = 0; iy < 2; ++iy )
        {
            for( int iz = 0; iz < 2; ++iz )
                corner[ix][iy][iz] = Point( pt.x + ix*cwidth, pt.y + iy*cwidth, pt.z + iz*cwidth );
        }
    }
}

void Cube::show() const
{
    for( int ix = 0; ix < 2; ++ix )
    {
        for( int iy = 0; iy < 2; ++iy )
        {
            for( int iz = 0; iz < 2; ++iz )
            {
                corner[ix][iy][iz].print();
            }
        }
    }
}
David W 131 Practically a Posting Shark

@Hafiz ... welcome to Dani's.

Please note:
the post you added to was already 4 years old ...
so best to start your own new thread.

And it's generally a good idea to NOT 'hijack' another persons post ...
so please start you own new thread if you want more help.

You do not need here to include <cstdio.h>
// Note: <stdio.h> is typically for C code //

What you need to include is <cctype> // re. tolower, isalpha //

And to keep code portable, not good to use system calls ... so ...
you may like to see this revision:

// countRepeatCharsInString.cpp //

#include <iostream>
#include <cctype> // re. tolwer, isalpha

const int NUM_LETS = 26;



int main()
{
    // initial all to 0 //
    int count[NUM_LETS] = { 0 }; // this is all that's needed here

    //now the interactive bit
    std::cout << "Enter a line of text : " << std::flush;
    std::string line;
    std::getline( std::cin, line );

    for( size_t i = 0; i < line.size(); ++ i )
    {
        int curChar = tolower( line[i] ); // letters "are int's" in C/C++ //
        if( isalpha(curChar) )
        {
            ++ count[curChar - 'a']; // get int in range 0..25 //
        }
    }

    for( size_t i = 0; i < NUM_LETS; ++ i )
    {
        if( count[i] ) // just show counts of letters that are there //
            std::cout << "There were " << count[i]
                      << " occurences of " << static_cast< char >(i + 'a') …
David W 131 Practically a Posting Shark

Or ... maybe ... something like in this recent example ... is what you are aiming to do ?

https://www.daniweb.com/programming/software-development/threads/500762/need-help-starting-this-program#post2189803

You make like to see this modification to the demo ... that also shows the destructors being called.

Note the use of new / delete here ... and the use of 'pointers' ...
(i.e an array of pointers.)

// airCraft2.cpp //

#include <iostream>


using namespace std;


class AirCraft
{
public:
    AirCraft( int e = 1 , int s = 1 ) : engines(e), seats(s) {}
    int get_engines() const { return engines; }
    int get_seats() const { return seats; }

    virtual ~AirCraft() { cout << "AirCraft dtor was called ...\n"; }

    virtual void print() const = 0;
private:
    int engines;
    int seats;
} ;


class Fighter : public AirCraft
{
public:
    Fighter( int e=1, int s=1, int g = 1 ) : AirCraft::AirCraft( e, s ), guns(g) {}

    ~Fighter() { cout << "Fighter dtor was called ...\n"; }

    void print() const
    {
        cout << "engines = " << get_engines()
             << ", seats = " << get_seats()
             << ", guns = " << guns << endl;
    }
private:
    int guns;
} ;

class Freight : public AirCraft
{
public:
    Freight( int e=2, int s=2, int w = 2000 ) : AirCraft::AirCraft( e, s ), lbs(w) {}

    ~Freight() { cout << "Freight dtor was called ...\n"; }

    void print() const
    {
        cout << "engines = " << get_engines()
             << ", seats = " << get_seats()
             << ", lbs = " …
David W 131 Practically a Posting Shark

This related demo may help you to get started ...

// airCraft.cpp //

#include <iostream>

using namespace std;

class AirCraft
{
public:
    AirCraft( int e = 1 , int s = 1 ) : engines(e), seats(s) {}
    int get_engines() const { return engines; }
    int get_seats() const { return seats; }

    virtual ~AirCraft() { cout << "AirCraft dtor was called ...\n"; }

    virtual void print() const = 0;
private:
    int engines;
    int seats;
} ;


class Fighter : public AirCraft
{
public:
    Fighter( int e=1, int s=1, int g = 1 ) : AirCraft::AirCraft( e, s ), guns(g) {}

    ~Fighter() { cout << "Fighter dtor was called ...\n"; }

    void print() const
    {
        cout << "engines = " << get_engines()
             << ", seats = " << get_seats()
             << ", guns = " << guns << endl;
    }
private:
    int guns;
} ;

class Freight : public AirCraft
{
public:
    Freight( int e=2, int s=2, int w = 2000 ) : AirCraft::AirCraft( e, s ), lbs(w) {}

    ~Freight() { cout << "Freight dtor was called ...\n"; }

    void print() const
    {
        cout << "engines = " << get_engines()
             << ", seats = " << get_seats()
             << ", lbs = " << lbs << endl;
    }
private:
    int lbs;
} ;



void test_it_out()
{
    AirCraft* a [10];
    a[0] = new Fighter();
    a[1] = new Freight( 4, 2, 10000 );

    a[0]->print();
    a[1]->print();

    delete a[1];
    delete a[0];
}

int main()
{
    test_it_out();
}
David W 131 Practically a Posting Shark

How does an array variable indexing expression differ from an array definition size expression?

Recall arrays in C/C++ are 0 based ...

i.e. if 'n' slots ...

first index i is at i = 0

nth index i is at i = n-1

David W 131 Practically a Posting Shark

Define an int array variable named arx with 3 slots, and stuff a 7 in the last slot
Is this correct?

int arx[2]=7; // NO //

or is it:

// int arx[3]; // this has 3 slots
// or better ... initial all to 0 at creation ...
int arx[3] = { 0 };
// then can update last slot ... (recall: C/C++ arrays start with index 0)
arx[2] = 7;
David W 131 Practically a Posting Shark

Note:

If you have NEVER BEFORE coded a solution to the problem of reading in some numbers from a text file of numbers ... and then displaying the data in the file ... and then, doing some processing of the data and displaying the results ... WITHOUT using a C++ class to handle ...

then FIRSTLY ...

you probably, BEST see/learn/practice ...

the use of functions and structured programming,
as demo'd at the link I supplied:
http://developers-heaven.net/forum/index.php/topic,2019.0.html

David W 131 Practically a Posting Shark

Yes :)

That was the first step :)

If you enter a file name of a pre-existing text file ... a file that you already made and placed there in the same folder as where the executable file is running ... it will then, read that file, a then display it ... as per the code ... Recall I said: this demo is a a demo of just some first steps.)

So, maybe with a text editor program that comes with Windows OS, like notepad.exe, place a text file, with say the (very original) name of: "numbers.txt" in your working folder ... the folder where the .exe file will be placed after you compile your program.

In that .txt file, you could place a 'copy/paste' of the numbers you were supplied in your problem's example output.

( i.e. the numbers are spaced out by 'white space(s) )

David W 131 Practically a Posting Shark

Do you know how to compile 'as a project' ?

If not ... then change the included file near the top of the main program file to read:

#include "numbers.cpp" // this firstly calls include numbers.h //

Then make sure the 2 files have correct file names
numbers.cpp
numbers.h

Then make sure all 3 files (the above 2 and the main program file) are in the same folder/directory where your compiler can easily find then ... when it starts to compile the main program

David W 131 Practically a Posting Shark

Or with NO dynamic memory (and a private cal_stats() member called by show_stats() ... at the top before printing the stats) :

#ifndef NUMBERS_H
#define NUMBERS_H

class Numbers
{
private:
    static const int capacity = 20;
    int ary[capacity];
    int size;
    int min, max, sum;
    void cal_stats();
public:
    Numbers() : size(0), sum(0) {}
    void clear()
    {
        size = sum = 0;
    }

    bool read_from_user_file();
    void show_ary() const;
    void show_stats();
} ;

#endif
David W 131 Practically a Posting Shark

This could be a first step (compile all 3 files as a project) :

file 1)

// file name: numbers.h //

/*
    No global variables should be used in this program.

    One method named "read from user file"
    which will ask the user to input a filename
    and will then read from 1 to 20 integers from that file

    Second method will display the values read in

    Third method will calculate the statistics
    and store these in the appropriately named variables
    that are also to be declared in the class

    Fourth method will display those statistics from those variables
*/

#ifndef NUMBERS_H
#define NUMBERS_H

class Numbers
{
private:
    int* ary;
    int size;
    static const int capacity;
    int min, max, sum;
public:
    Numbers() : ary(new int[capacity]), size(0), sum(0) {}
    ~Numbers() { delete [] ary; size = 0; sum = 0; }

    bool read_from_user_file();
    void show_ary() const;
    void cal_stats();
    void show_stats() const;
} ;

#endif

file 2)

// file name:  numbers.cpp //

#include "numbers.h"

#include <iostream>
#include <fstream>
#include <string>


const int Numbers::capacity = 20;


// returns true if file opened ok, else returns false
bool Numbers::read_from_user_file()
{
    std::cout << "Enter a file name to read (ex. \"numbers.txt\"): "
              << std::flush;
    std::string name;
    getline( std::cin, name );
    std::ifstream fin( name.c_str() );
    if( fin )
    {
        while( size < capacity && fin >> ary[size] )
        {
            sum += ary[size];
            ++size;
        }
        fin.close();
        return true;
    }
    // else
    std::cout << "There was a problem reading from file " << name << '\n';
    return …
David W 131 Practically a Posting Shark

Take it in steps ... Firstly just read in the file and display it back ... Get that working before you add any other methods.

You may like to look here for some more ideas ...
http://developers-heaven.net/forum/index.php/topic,2019.0.html

David W 131 Practically a Posting Shark

Hi @rose_2,

Do you know how to code an "Hello World" type program in C++ ?

If you do, then you can prompt for input.

Then the next thing ... is to code to take in some number ...
and then to take in numbers in a loop and to sum them up.

There are actually many ways to code for this...
but a simple way is demo'd at the following link:

Six Fast Steps to Programming in C++
http://developers-heaven.net/forum/index.php/topic,2019.0.html

But code your own version of a solution for your problem ...
and if you get stuck,
then you will need to show us the code you have tried so far.

Then ... we can see how to help you.

David W 131 Practically a Posting Shark

Hey @tgreiner

Sorry about the duplicate post ... I did not notice that duplicate until just now ...

If you will check my posts you will see that they are all meant to be instructive ...

It will be good for you to isolate the code (do you need some debugging tips?) where you think the problem lays ...

Then code a test program to run that isolated code to verify that.

Then if you still cannot find/fix the bug ... all you need to do is show us that much-reduced code snippet.

Please understand that that was what was intended by bolding the words ...

the code IN QUESTION

Shalom,
David

David W 131 Practically a Posting Shark

But ... I think you still have same 'logic errors' ?

Take a look:

/* gameStudent151020.c */


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

const int MAX_TOT = 100;
const int MIN_TOT = 25;


/* 3 utilites used here... */
int takeInInt( const char* msg, const int min, const int max );
int takeInChr( const char* msg );
int more();
/* used for game */
void showDice( const int face );
void playGame();



int main()
{
    do
    {
        playGame();
    }
    while( more() );

    return 0;
}




void playGame()
{
    int gameTotal = 0, playerOne = 0, playerTwo = 0;
    int playerNum = 1; /* start with player one */

    srand( time(0) );

    printf( "Welcome to *** THE GAME OF PIG ***\n\n" );

    gameTotal = takeInInt( "What would you like to be the 'end-game' total? ", MIN_TOT, MAX_TOT );

    while( playerOne < gameTotal && playerTwo < gameTotal )
    {
        int roll;
        if( playerNum == 1 )
        {
            printf( "\nIt's player one's turn ... do you want to roll or hold " );
            do
            {
                roll = takeInChr( "(r/h) ? " );
            }
            while( !( roll == 'r' || roll == 'h') );

            if( roll == 'r' )
            {
                const int value = rand() % 6 +1;
                showDice( value );
                if( value == 1 ) /* switch players */
                    playerNum = 2;
                else /* only count score if value NOT 1 */
                    playerOne += value;
            }
            else
            {
                printf( "Alright, hold it is \n" );
                playerNum = 2;
            }
        }
        else
        {
            const …
David W 131 Practically a Posting Shark

One way to handle your problem of comparing decimal values to see if they are equal could be ...

If your largest number to handle is (about) 99999.9999 ...
then if you multiply all decimals by 10000 ...
add 0.5 to round up
then truncate to an int
then note that 1000000000 will easily fit into a 32 bit int (on any 32 or 64 bit PC)
then when comparing numbers, you can just make easy int comparisons

Then divide these scaled up values ... i.e. divide each by 10000.0
to convert them back to a type double of the original scale.

But the example below shows a more common way to handle ...

// closeEnough.cpp //


#include <iostream>
#include <iomanip>
#include <cmath>   //to use sin function

using namespace std;


const double EPSILON = 5.00e-5;

bool closeEnough( const double test, const double cmp )
{
    return fabs( cmp - test ) < EPSILON ;
}


double fx( const double x )
{
    return sin(x) - 5*x + 2;
}




int main()
{
    double y = fx(0.495);

    cout << fixed << setprecision(4);
    cout<< "fx(0.495) = " << y << ' ';

    if( closeEnough( y, 0 ) ) cout << "'i.e. close enough to' zero";
    else cout << "i.e. NOT 'close enough to' zero";
}
David W 131 Practically a Posting Shark

An other way to approach your problem is to 'huffle the deck' before dealing it out ...

Take a look:

/* 52Cards.c */

/*
    You can find file "readline.h" at:
    http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864

    You can find file "Cvec.h" at:
    http://developers-heaven.net/forum/index.php/topic,2580.0.html

*/

#include "readLine.h" /* re. myAssert */
#include <time.h>


const char kinds[] = {'S', 'C', 'H', 'D'};
const char values[] = {'2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'};


typedef struct
{
    char kind;
    char val;

} Rec;

void freeVrec( Rec* p )
{
    /* NO dynamic memory was used here, so NONE to free  ... */
}


/* NEED BOTH definitions above: typedef Rec  and  freeVrec ...
   and then can include ... */

#include "Cvec.h"

#define Card Rec /* equate */


void getNewDeck( Cvec* cards )
{
    int i, j;
    for( i = 0; i < 4; ++ i )
    {
        for( j = 0; j < 13; ++ j )
        {
            Card c;
            c.kind = kinds[i];
            c.val = values[j];
            push_backCvec( cards, &c  );
        }
    }
}
void shuffleDeck( Cvec* cards )
{
    int i, j, count = cards->size;
    Card tmp;
    while( count-- )
    {
        i = rand() % cards->size;
        j = rand() % cards->size;

        /* swap */
        tmp = cards->ary[i];
        cards->ary[i] = cards->ary[j];
        cards->ary[j] = tmp;
    }
}
void showCards( const Cvec* cards )
{
    int i;
    for( i = 0; i < cards->size;  )
    {
        printf( "%c%c  ", cards->ary[i].val, cards->ary[i].kind ) ;
        if( ++i % 13 == 0 ) putchar('\n'); …
JamesCherrill commented: Definitely the best approach +15
David W 131 Practically a Posting Shark

If you will carefully re-read ...
@tinstaafl

It's pretty hard to say where the problem could be
without seeing the code IN QUESTION.

David W 131 Practically a Posting Shark

It's pretty hard to say where the problem could be
without seeing the code IN QUESTION.

David W 131 Practically a Posting Shark

This link may give you some more ideas about a way to proceed ...

http://developers-heaven.net/forum/index.php/topic,2585.0.html

David W 131 Practically a Posting Shark

Why don't you start fresh and code a little name, phone_number and email type data base?

You could use a C++ vector container to hold all the data records (objects)

You might start out with something like this:

class Person
{
public:
    Person( const string& name="", const string& phone="", const string& email="" )
    : name(name), phone(phone), email(email) {}
    // other stuff //
private:
    string name;
    string phone;
    string email;
} ;
David W 131 Practically a Posting Shark

Dani ...

I think we have a 'malicious stalker' haunting your normally nice and friendly web space ?