David W 131 Practically a Posting Shark

Take a look:

# str.istitle.py #

myStrs = [ "Sam S. Smith", "Ann a. anderson", "Anne Anderson" ]

mySet = set(myStrs) # pretend this is your big dictionary of names

for item in myStrs:
    print( "'" + item +"'.istitle() is", item.istitle() )

print()

for item in myStrs:
    print( "'" + item +"'[0] == A is", item[0] == 'A' )

print()    

for item in myStrs:
    if item[0] == 'A':
        if item in mySet:
            print( "'" + item +"'[0] == A is", item[0] == 'A' )
            print( item, "is in", mySet )
David W 131 Practically a Posting Shark

You may have to hunt the web for a big file of names ...

When you find suitable ones process and merge them into one big set (of unique names)

(Actually ...
just keep names that begin with 'A' in your set of processed names.)

Now just look up each word that beings with 'A' to see if it is in that set.

(Set look up times are very short.)

David W 131 Practically a Posting Shark

For starters, you might test each word to see if it begins with 'A' ?

If it does ...
then might look it up in a dictionary of just names to see if it is a name?

David W 131 Practically a Posting Shark

But if you are using ... not excessively large,

'pre-fixed max-size receipt tapes' ...
on each of your simulated 'cash-registers' ...

probably a much better idea than messing about with dynamic memory,
would be to just use an array,
pre-fixed at compile time,
to hold each 'max-sized receipt tape'

Maybe (an edit of your code) could be ... a little something like this:

// classCashRegister3.cpp //

#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>

using namespace std;

////////////////////////////////////////////////////
// done here ... so can easily change and re-compile
////////////////////////////////////////////////////
const int MAX_NUM_RECEIPTS = 10;
const double TAX_RATE = 1.13;

struct Item
{
    string name;
    double price;
} ;

const Item ITEMS[] =
{
    { "Hammers", 10.99 }, { "Levels", 19.99 },
    { "Screwdrivers", 8.99 }, { "Tape Measures", 4.99 },
    { "Wrenches", 10.99  }
} ;

const int NUM_ITEMS = sizeof(ITEMS) / sizeof(Item) ;
////////////////////////////////////////////////////


// a utility used here to facilitate VALID integer input //
int takeInInt( const string msg )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
            break;
        else
        {
            cout << "ERROR! Integers ONLY here please ...\n";
            cin.clear(); // clear error flasgs
            cin.sync(); // 'flush' cin stream ...
        }
    }
    return val;
}
///////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
class Register
{
private:

    struct Receipt
    {
        double total; // to hold dollar total for each order

        // to hold the quantity of each item ordered for an order, i.e. a receipt
        int …
David W 131 Practically a Posting Shark

And also ...

for starters ...

you need a destructor (to plug your memory leak) ...
and probably a copy constructor ...
and your code for the overloaded assignment operator is 'interesting' :)

Fix the above first ...

then (any) other errors will manifest more clearly :)

David W 131 Practically a Posting Shark

An other way to learn is by observing the coding steps ... and code ... of master coders.

Then trying to implement what you have learned to solve similar problems.

Some prof's will, at first,
outline the code-developement/code-testing steps ... step by step.

Then you can very easily 'see' how the solution process is progressing,
as you code/test each next part,
to be added in ... in the develop/test process.

Then you can use a similar process to layout and build/test your own, top-down designed ... and built, bottom up solutions.

I would recommed a text like this one, by a seasoned teacher and master coder:

http://plantation-productions.com/Webster/www.writegreatcode.com/index.html

David W 131 Practically a Posting Shark

This example may help you to get started ...

// classCashRegister.cpp //  // 2015-02-27 //

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

using namespace std;

// a utility useful here ... //
int takeInInt( const string msg )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
            break;
        else
        {
            cout << "ERROR! Integers ONLY here please ...\n";
            cin.clear(); // clear error flasgs
            cin.sync(); // 'flush' cin stream ...
        }
    }
    return val;
}



struct MyPair
{
    string name;
    double price;
    // ctor...
    MyPair( const string& name, double price ) : name(name), price(price)  { }
} ;


const MyPair ITEMS[] =
{
    MyPair("Hammers", 10.99),  MyPair("Wrenches", 10.99),
    MyPair("Levels", 19.99),  MyPair("Tape Measures", 4.99),
    MyPair("Screwdrivers", 8.99)
} ;

const int NUM_ITEMS = sizeof(ITEMS) / sizeof( MyPair );

struct Order
{
    int item[NUM_ITEMS]; // to hold quantity of each item ordered //

    // default ctor...
    Order() { for( int i = 0; i < NUM_ITEMS; ++ i ) item[i] = 0; }

    double get_total() const
    {
        double sum = 0;
        for( int i = 0; i < NUM_ITEMS; ++ i )
             sum += item[i] * ITEMS[i].price;
        return sum;
    }
    void takeIn()
    {
        for( int i = 0; i < NUM_ITEMS; ++ i )
        {
            item[i] = takeInInt("How many " + ITEMS[i].name + ": ");
        }
    }
} ;


class Register
{
    vector< Order > myOrders;
    double sum;

public:
    Register( int max_num ) { myOrders.reserve(max_num); sum = 0; }

    void get_order() …
David W 131 Practically a Posting Shark

You need to re-read the 'problem' ...

Write a c++ program that does the following:
Create a Register class that can store all of the receipts
for the day and the totals for that register.

So ... each cash-register STORES each order (could use a struct for each order)

Thus ... could use a vector of struct to hold all orders for each cash-register
also could have a member to track the running dollar sum of orders so far

David W 131 Practically a Posting Shark

or? .... could use latest Python 3 with:

import sqlite3

David W 131 Practically a Posting Shark

This is such a small problem that it seems more appropriate to just do it all in one short file:

Note: the print logic flow can be made clear here by using two bool 'flags' to track what has already been printed:

for( int i = 1; i < 101; ++i )
{
    bool global = false,
         logic = false;

    if( i % 3 == 0 ) { global = true; cout << "global"; }
    if( i % 5 == 0 ) { logic = true; cout << "logic"; }

    if( !(global || logic) ) cout << i;

    cout << endl;
}
David W 131 Practically a Posting Shark

Your friend will need to have a compatible OS for your executable file to run on that OS.

David W 131 Practically a Posting Shark

Sometimes looking at some similar problem code examples can give you ideas how to get started ...

Suppose you had a Money struct ...

typedef struct
{
    unsigned dollars;
    unsigned cents;

} Money ;

And you wanted to code a function to take in data from a keyboard user to fill up this struct ...

You could code that like this ...

Money takeInMoney()
{
    Money m;
    m.dollars = takeInValid( "Enter dollars : " );
    m.cents   = takeInValid( "Enter cents   : " );

    if( m.cents >= 100 ) /* normalize */
    {
        m.dollars += m.cents / 100;
        m.cents %= 100;
    }

    return m;
}

Of couse, you would have to have already definded this function, before you could call it ...

/* a simple student way to handle numeric input ...
   so program won't crash on bad input */
unsigned takeInValid( const char* msg )
{
    unsigned val = 0;
    while( 1 ) /* loop forever until break is reached ... */
    {
        printf( msg ); fflush( stdout );

        if( scanf( "%u", &val ) == 1 && getchar() == '\n' )
            break;
        else
        {
            printf( "\nUnsigned integer input only here please ...\n" );
            while( getchar() != '\n' ) ; /* flush stdin ... */
        }
    }
    return val;
}

Now if you wished to sum up an array of 'Money' type values, that could be handled like this:

Money sumAll( const Money deposits[], unsigned size )
{
    Money tot = { 0, 0 …
senait.kifle.127 commented: Appreciated... Now I got it! +0
David W 131 Practically a Posting Shark

And here is an 'homegrown' Stack example, revised from your example, that you can use to compare and fix up your stack class (it uses the above class SLList) :

(Note the overloaded == is supplied in the derived class, since the base class did not have it.)

// STACK.H //  // needs a C++11 compiler //

// class definition using private inheritance of class SLList //

#ifndef Stack_h
#define Stack_h

#include "SLList.h"

template< typename STACKTYPE >
class Stack : private SLList< STACKTYPE >
{
public:

    void push( const STACKTYPE& data )
    {
        this->push_front( data )  ;
    }

    const STACKTYPE& top()
    {
        return this->top();
    }

    bool pop()
    {
        return this->pop_front();
    }

    bool operator == ( Stack& other )
    {
        if( this->size() != other.size() ) return false;
        // else ...
        auto it = this->begin(), it2 = other.begin();

        while( it != this->end() )
        {
            if( *it != *it2 ) return false;
            ++it, ++it2;
        }
        // if reach here ...
        return true;
    }

    void print()
    {
        std::cout << "The stack is: ";
        for( auto it = this->begin(); it != this->end(); ++it )
             std::cout << *it << ' ';
    }
} ;
#endif

And you can see that there were only a few simple edits made to the 'test program' ... to enable the use of the 'homegrown stack' :

//  testIfPalindrome2.cpp //  // needs C++11 compiler //

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype> // for C++ ... but Note:  C uses <ctype.h> //

#include "STACK.H"


using namespace std; …
David W 131 Practically a Posting Shark

For example, using the STL stack (with the STL list), this demos a 'proof of concept' ... and a way to trim your code some more ... since you are already using C++11 ...

//  testIfPalindrome.cpp //  // needs C++11 compiler //

#include <iostream>
#include <string>
#include <algorithm>
#include <cctype> // for C++ ... but Note:  C uses <ctype.h> //

#include <list>
#include <stack> // developed first with a KNOWN working stack container //

using namespace std;


// some utilities used here ...

string takeInString( const string& msg = "" )
{
    cout << msg << flush;
    string val;
    getline( cin, val );
    return val;
}
int takeInChr( const std::string& msg = "" )
{
    string reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChr( "More (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}
bool hasDigits( const string& toTest )
{
    for( auto e : toTest )
        if( isdigit(e) )
            return true;

    // else ... if reach here ...
    return false;
}



int main()
{
    cout << "This program tests if "
            "a string is a 'palindrome' ...\n\n";
    do
    {
        string input;
        for( ; ; )
        {
            input = takeInString( "Enter a line of text, without "
                                  "any numbers in it, to be "
                                  "tested:\n" );
            if( hasDigits( input ) )
            {
                cout << "\nInput can not have any numeric characters"
                     << ", please try again.\n\n";
            }
            else
                break; …
David W 131 Practically a Posting Shark

Perhaps you do not 'see' my method here ... It was to GIVE you some working code examples (just at first for a SLList class) ... so that you could then compare each working method there ... to yours ... and thus to 'see' ... your several coding errors.

The methods for the push_front and push_back ACTUALLY were fixed, by your futher fix re. this common line in each method:

lastPtr = newPtr;

But, like I stated at the top, there were still several other errors in your single-linked list class.

After I posted the above example, code, I noticed a line was missing in the nested iterator class. That class should be like this:

class iterator
{
private:
    Node< NODETYPE >* ptr;
    friend class SLList< NODETYPE >; // this line was missing //
public:
    iterator& operator ++ () { ptr = ptr->nextPtr; return *this; }
    iterator& operator ++ ( int dummy ) { ptr = ptr->nextPtr; return *this; }
    bool operator !=  (const iterator& it2)  const { return  ptr != it2.ptr; }
    const NODETYPE operator * () const { return ptr->data; }
    NODETYPE& operator * () { return ptr->data; }
} ;

Firstly ...

get your SLList working and tested ok.

Create a simple test program like the example I provided that tests out all the functionality in your list class to 'prove' to yourself that each part is working correctly.

Then ... and only then, work on using that list in some other program.

David W 131 Practically a Posting Shark

Glad to see that you fixed-up the insert at front and back methods ... that's really great.

Now ... here's how I might start out to code a SLList in C++11 ... using some of your variable names and style, but changing several method names to be more like the names used in the STL. Note the ++len when adding list elements ... or ... --len when deleting list elements ... 'as we go'.

I also added an iterator class 'nested' inside of the SLList class.

Take a look:

Firstly the file: "LISTNODE.H"

// LISTNODE.H //  // needs C++11 compiler //

#ifndef LISTNODE_H
#define LISTNODE_H

//forward declaration of class SLList is required to announce that class
template< typename NODETYPE > class SLList;

template< typename NODETYPE >
class Node
{
private:
    friend class SLList< NODETYPE >;

    NODETYPE data;
    Node< NODETYPE > *nextPtr;
public:
    // value ctor...
    Node( const NODETYPE& info ) : data(info), nextPtr(nullptr)
    {}
} ;

#endif

Then the file: "SLList.h"

// SLList.h //  // needs C++11 compiler //


#ifndef SLLIST_H
#define SLLIST_H

#include "LISTNODE.H"

#include <iostream>
#include <stdexcept>

template < typename NODETYPE >
class SLList
{
public:

    //default constructor
    explicit SLList(): firstPtr(nullptr), lastPtr(nullptr), len(0) {}

    //destructor
    ~SLList()
    {
        clear();
        std::cout << "All nodes destroyed\n";
    }

    void push_front( const NODETYPE& value )
    {
        Node< NODETYPE >* newPtr = getNewNode( value );

        // faster running code if firstly handle most likely case ...
        if( len ) 
        {
            newPtr->nextPtr = firstPtr;
            firstPtr = newPtr;
        }
        else
        {
            lastPtr = …
David W 131 Practically a Posting Shark

Not fixed yet ...

(Note: there are other problems besides these 2 ...)

What is wrong here?
(See changes/added comments to your code.)

//insert node at front of List
void insertAtFront(const NODETYPE& value)
{
    ListNode<NODETYPE> *newPtr=getNewNode(value);

    if (isEmpty()) //List is empty
    {
        firstPtr = newPtr;
        //lastPtr = nullptr; // NOT what you want //

        lastPtr = ?? //hint: how many nodes now exist ?


        //newPtr->nextPtr = lastPtr; // really? NO line needed here anyway //
    }
    else // List is not empty
    {
        newPtr->nextPtr = firstPtr; // GOOD
        firstPtr = newPtr; // GOOD
    }

    //newPtr->nextPtr=nullptr; // NO, this undoes link //
}

And here ...

//insert node at back of List
void insertAtBack(const NODETYPE& value)
{
    ListNode<NODETYPE> *newPtr=getNewNode(value);

    if (isEmpty())
    {
        firstPtr=newPtr;
        // lastPtr=nullptr; // SAME problem as above

        lastPtr = ?? ;// hint as above

        // newPtr->nextPtr=lastPtr; // NO, and do not need any line here anyways //
    }
    else //list is not empty
    {
        lastPtr->nextPtr = newPtr;                  
        lastPtr = newPtr;
    }
    // newPtr->nextPtr=nullptr; // redundant // 
}

So just (further) fix up this ONE line in both methods:
lastPtr = ?? //
and you will be ok with these two methods.

Hint:
I would add a private member to your list to track the size ...

size_t len;
// then public method size is so easy :)
size_t size() const { return len; }
David W 131 Practically a Posting Shark

Here is the error message I get: "Error: Unable to access jarfile myJar.jar"

So ... try moving the file "myJar.jar" to where it is in the path expected.

David W 131 Practically a Posting Shark

If your large data file has data that appears as consistently as your example would suggest, then you might use this simple approach:

# processlargeFile.py #

FNAME = 'largeFile.txt'

try:
    with open( FNAME ) as f:
        count = 0
        data = [] # get an empty list
        line = f.readline()
        while line:
            line = line.rstrip()
            if line and line[0] != '.': # if not empty and ...
                count += 1
                #print( line )
                if count == 1: # get date/time data
                    data.append( line[0:24] ) #get the first 24 char's
                elif count == 2: #get name
                    data.append( line[7:] ) #get all the chars beginning at index 7
                elif count == 3: #get last name
                    data.append( line[11:] )
                elif count == 4: #get age
                    data.append( line[6:] )
                elif count == 5: #get height, so done this record, so ...
                    data.append( line[9:] )
                    count = 0
                    #print( data )
                    print( ','.join( data ) )
                    #print()
                    data = []

            line = f.readline()
except:
    print( 'There was a problem opening/reading file', FNAME )

If your large data file lacks the regularly repeating data pattern needed above, perhaps you could first then pre-process the data so that it complies.

David W 131 Practically a Posting Shark

Just a quick scan and I noticed this:

(What is wrong here? Hint what is the tail node value after adding first node to list? What should it be?)

//insert node at front of List
void insertAtFront(const NODETYPE& value)
{
    ListNode<NODETYPE> *newPtr=getNewNode(value);   //new node

    if (isEmpty())                                  //List is empty
        firstPtr=lastPtr=newPtr;                    //new List has only one node
    else
    {
        //List is not empty
        newPtr->nextPtr=firstPtr;
        firstPtr=newPtr;
    }
}


//insert node at back of List
void insertAtBack(const NODETYPE& value)
{
    ListNode<NODETYPE> *newPtr=getNewNode(value);   //new node

    if (isEmpty())
        firstPtr=lastPtr=newPtr;                    //new List has only one node
    else
    {
        //list is not empty
        lastPtr->nextPtr = newPtr;                  //update previous last node
        lastPtr = newPtr;
    }
}
David W 131 Practically a Posting Shark

This is not the method that you really want to use ... is it?

    template<typename T>
    void glueAtEnd( List<T>& a, List<T>& b )
    {
        T value;
        while( !b.isEmpty() )
        {
            a.insertAtBack(b[0]);
            b.removeFromFront(value);
        }
    }

(Recall that I said that my example using STL list was a 'poor' emulation of what you really wanted to do.)

I presume that you want to update the 'tail Node next pointer' ... to point to the head Node of the list you wanted appended ... and to have the 2nd list head Node prev pointer to be updated to point to the tail Node in the 1st list ... yes/no?

If you are coding your own List class, you can code a member function (or a friend function) to do the above.

When the 2nd list has been 'glued' to the end of the first list, then you will want to 'fix' the head and tail and size private members of the 2nd list ... to then reflect that the 2nd list is now 'empty'.

When using cin for student type numeric input, I like to always validate the input and keep the cin error flags 'cleared' and the cin stream 'flushed' ... to prevent 'skipping' the next input because there was an error state or some char's like the '\n' char were left behind by the previous cin input call.

David W 131 Practically a Posting Shark

Ok ... you have multiple potential problems.

It is often best to solve them one at a time.

A 1st problem is your driver test program.

So here, I just use the STL list to show a ...
'proof of concept' ... working test program.

Once you have all the bugs out there ...

then with a well tested list ...
(i.e. after all aspects of that list are tested, except for the 'glue' part)

then attack the problem of your 'glue' function that joins two lists of your own home grown design.

Here is an example of a 'proof of concept' test program that uses the well tested STL list:

// glueTwoLists.cpp //

//  Program that takes two linked list objects and
// 'glues' second' list to end of first ...

#include <iostream>
#include <string>
#include <list>

using namespace std;

// some utilities used here ...

string takeInString( const string& msg = "" )
{
    cout << msg << flush;
    string val;
    getline( cin, val );
    return val;
}
char takeInChr( const std::string& msg = "" )
{
    string reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChr( "More (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}
int takeInValidInt( const string& msg )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
            break;
        else …
David W 131 Practically a Posting Shark

This demo of a menu -> choice pattern is simple and easily adapted to many student type menu -> choice type problems.

Note how it simply avoids the very common ...

beginning student problem

of 'dangling char's left in the cin stream' :

// showMenuTakeInChoice.cpp //

#include <iostream>
#include <string>


const std::string MENU =
    "1. Save a new password\n"
    "2. Display all passwords\n"
    "3. Exit\n\n"
    "Choose 1, 2, or 3: ";

char takeInChr( 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;
}

/*
bool more()
{
    if( tolower( takeInChr( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}
*/


int main()
{
    char choice;
    bool quit = false;
    while( !quit )
    {
        switch( (choice = takeInChr( MENU )) )
        {
            case '1':
                std::cout << "\n'1' is under construction"
                          << " ...\n\n";
            break;
            case '2':
                std::cout << "\n'2' is under construction "
                          << " ...\n\n";
            break;
            case '3':
                quit = true;
                takeInChr( "\nPress 'Enter' to "
                           "continue/EXIT ..." );
            break;
            default:
                std::cout << "\n'" << choice
                          << "' is NOT a valid choice "
                          << "here ...\n\n";
        }
    }
}
David W 131 Practically a Posting Shark

This demo of a menu -> choice pattern is simple and easily adapted to many student type menu -> choice problems.

Note how it simply avoids the very common ...

beginning student problem

of 'dangling char's left in the cin stream' :

// showMenuTakeInChoice.cpp //

#include <iostream>
#include <string>
// #include <cctype> //re. tolower


const std::string MENU =
    "1. Save a new password\n"
    "2. Display all passwords\n"
    "3. Exit\n\n"
    "Choose 1, 2, or 3: ";

char takeInChr( 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;
}

/*
bool more()
{
    if( tolower( takeInChr( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}
*/


int main()
{
    char choice;
    bool quit = false;
    while( !quit )
    {
        switch( (choice = takeInChr( MENU )) )
        {
            case '1':
                std::cout << "\n'1' is under construction"
                          << " ...\n\n";
            break;
            case '2':
                std::cout << "\n'2' is under construction "
                          << " ...\n\n";
            break;
            case '3':
                quit = true;
                takeInChr( "\nPress 'Enter' to "
                           "continue/EXIT ..." );
            break;
            default:
                std::cout << "\n'" << choice
                          << "' is NOT a valid choice "
                          << "here ...\n\n";
        }
    }
}
David W 131 Practically a Posting Shark

Further to comment by @vegaseat ...

you can print out ...

print( type( in_file ) ) # debugging Python object types #
print( type( indata ) )

You may like to see this Python 3 revision ...
(that uses Python exceptions to handle the 'abort' option)

# copyFileToFile.py #

from os.path import exists
import os

##from sys import argv
##script, fnameIn, fnameOut = argv

fnameIn, fnameOut = 'myData.txt', 'myDataCopy.txt'

class AbortCopyException( Exception ):
    pass

try:
    with open( fnameIn ) as fin:
        #print( type(fin) )
        inData = fin.read()
        #print( type(inData) )
        print( "There are {} bytes of data in file {} to copy.".
               format( len(inData), fnameIn ) )

        if exists( fnameOut ):
            while( True ):
                ans = input( "\nPress 'Return' to continue and to "
                             "OVERWRITE \nexisting output file: '{}'"
                             "\nOR ... \nPress 'a' to abort ?  ".
                             format( fnameOut ) ) #argv[2]
                if ans in '\n':
                    break
                if ans.lower() == 'a':
                    raise AbortCopyException()
                print( "\nMust enter 'a' or press 'Enter' ..." )

        try:
            with open( fnameOut, 'w' ) as fout:
                print( "\nCopying file '{}' to file '{}' ...".
                       format( fnameIn, fnameOut ) )
                fout.write( fin.read() )
            print( "Copying now done." )

        except:
            print( "There was a problem opening or reading file {}".
                   format( fnameOut ) )
except( AbortCopyException ):
    print( "Aborting copy ... " )
except:
    print( "There was a problem opening or writing file {}".
           format( fnameIn ) )


input( "\nPress 'Enter' to continue/EXIT ... " )
David W 131 Practically a Posting Shark

re. the other part of your question ...

the use of typedef can either be

helpful to your code flow

or

hinder (hide from) your understanding

what the code is doing

For an example of common use:
One can easily make iterators to arrays using typedef

For an example of questionable/controversial use:
some hiding of pointers with typedef

There ... now you can:

Google typedef hiding pointer problem

and see here:

http://discuss.fogcreek.com/joelonsoftware1/default.asp?cmd=show&ixPost=10506

David W 131 Practically a Posting Shark

I really can not tell without seeing your exact code and having the exact same testing setup.

But ... C++ code that is well written ... to accord to standard C++ ... will (normally) compile ok and run ok on any other C++ standard complient system.

David W 131 Practically a Posting Shark

You need to add ...

#include <cstdlib> // re. exit

but do not use exit ...

It's not really needed ...
Just return some none 0 error (flag) value, if you wish.

(The code already prints an error message if there was a file finding/opening problem.)

You do not need to code for the overloaded =
The default supplied here is just fine.

You do not need the code for:

/*
std::ostream& operator<<(std::ostream& op,const Choices& choice)
{
    //print the string corresponding to the value of enum type Choices
        op << SELECT[choice]; //print output
    return op;
}
*/

it is not used ... since the SELECT[i] string is NOW printed

When I compiled you code on my PC it compiled ok and seemed to run op ... (quick test only)

David W 131 Practically a Posting Shark

Ok ... here is a 'debugging' problem / solution process to try :)

Take my code ...
compile
check

Then replace blocks/functions with 'comparable code'
from your program ...
compile and check ...
to find the code problem

David W 131 Practically a Posting Shark

you still did not offer a solution to my problem of initializing an object with no parameters (using the default values in the constructor).

Please note the changes to your erroroneous (ctor) code that were made here ...

HardwareRecord::HardwareRecord( int account, string name, string description, double price )
: myAccountNumber(account), myName(name), myDescription(description), myPrice(price)
{
    /* *** NO ***
    setAccountNumber(account);
    setName(name);
    setPrice(price);
    setDescription(description);
    */
}

What type of computer are you working on? If it's a mac, I can compress my project for you to check on your compiler.

I use Window 7 OS on ACER Laptop with Intel i5 CPU (64-bit OS)

Your code worked just fine, even when I uncommented the line

HardwareRecord temp;

When I just now made these code changes ...
all compiled and output was as expected ... ok.

// Can do this later ... //
void wipeRecords( /* fstream& theFile*/ )
{

    HardwareRecord temp; 
    cout << "\nInside wipeRecords default ctor called ok ... \n"; // prints ok when choice 0 called //
    /*
    temp.setPrice(10.52);
    cout << temp.getPrice() << endl;
    for (int i = 0; i < 100; i++)
    {
        //convert record from binary and assign to temp
        //make temp "wipe itself"
    }
*/

On mine, I get the error with No matching constructor
for initialization...

I thought you said (the code I sent) worked ok on (both) your compiler(s) ?

David W 131 Practically a Posting Shark

Did you not read, research ... and then understand the added comments?

I understand everything except for your usage of size_t, and the clearing of the cin error flags. What would happen with it if a person inputs a value less than 0?

Accepting only unsigned numbers eliminates the need to add exception code to reject negative values input ... since cin will flag as bad any neg values input and can handle by ...

if( cin >> val ) then
else ...

Once cin has error flags set ... until you clear them no more input will work ok.

Compiler error messages can sometimes be quite 'tricky' and then 'misleading'...

That is why I like to also develope in small incremental code steps ... always keeping a copy of the last 'working step' ...

This can help to locate the section of (most probably the new) code where the code error lies ...

Did you see that you were also missing a header file?

Did you try to compile the code I provided to see if all your compilers handled it ok or not?

Clean simple logic code is usually easier to debug :)

David W 131 Practically a Posting Shark

I think you can really clean up your code still and simplify it lots ...

Take a look at this and see the added comments ...

file: HardwareRecord.h

// file: HardwareRecord.h //

#ifndef HARDWARE_RECORD_H
#define HARDWARE_RECORD_H

#include <iostream>

class HardwareRecord
{
public:
    //constructor
    HardwareRecord( int account =0, std::string name ="",
                       std::string description ="",
                       double price =0.0 );

    // default copy ctor... is ok here ...
    //HardwareRecord operator = ( const HardwareRecord& );

    // 'set' and 'get' functions
    void setAccountNumber(size_t);
    size_t getAccountNumber() const;

    void setName(std::string);
    std::string getName() const;

    void setPrice(double);
    double getPrice() const;

    void setDescription(std::string);
    std::string getDescription() const;

    void wipeRecord(); //set everything to blank

private:
    size_t myAccountNumber;
    std::string myName;
    std::string myDescription;
    double myPrice;
};

#endif

file HardwareRecord.cpp

//  file HardwareRecord.cpp

#include <stdexcept>      // std::invalid_argument

#include "HardwareRecord.h"
// #include <iostream> // included above

using std::string;
using std::invalid_argument;

/* default copy ctor... is ok here ...
HardwareRecord HardwareRecord::operator= ( const HardwareRecord& aRecord )
{
    myAccountNumber=aRecord.myAccountNumber;
    myName=aRecord.myName;
    myDescription=aRecord.myDescription;
    myPrice=aRecord.myPrice;

    return *this; //allow for cascaded overloading
}
*/

HardwareRecord::HardwareRecord( int account, string name,
                                string description,
                                double price )
    : myAccountNumber(account), myName(name),
    myDescription(description), myPrice(price)
{
    /* *** NO ***
    setAccountNumber(account);
    setName(name);
    setPrice(price);
    setDescription(description);
    */
}



void HardwareRecord::wipeRecord()
{
    setAccountNumber(0);
    setName("");
    setPrice(0);
    setDescription("");
}

void HardwareRecord::setAccountNumber(size_t num)
{
    /*
    if (num < 0)
    {
        throw invalid_argument("The account number is not in the valid range (greater or equal to 0)");
    }
    else
    {*/
        myAccountNumber = num;
    //}
}

size_t HardwareRecord::getAccountNumber() const
{
    return myAccountNumber;
}

void HardwareRecord::setName(string name)
{

   myName=name;

}

string HardwareRecord::getName() const
{ …
David W 131 Practically a Posting Shark

Or ... a very simple way to start could be like this ...
(that lets readily you use all the STL vector member functions)

// schools.cpp //

#include <iostream>
#include <string>
#include <vector>

using namespace std;


struct Student
{
    string lname, fname;
} ;


ostream& operator << ( ostream& os, const Student& st )
{
    return os << st.lname << ", " << st.fname;
}


int main()
{
    // 'construct' school vs to have 3 floors
    vector < vector < vector < Student > > > vs ( 3 );

    // make each floor to have 5 classes
    for( int i = 0; i < 3; ++ i )
        vs[i].resize(5);

    // reserve room in each class for 20 students
    for( int i = 0; i < 3; ++ i )
    {
        for( int j = 0; j < 5; ++ j )
        vs[i][j].reserve(20);
    }

    // assign peter pan to floor 2, room3, seat 1
    Student tmp;
    tmp.lname = "Pan", tmp.fname = "Peter";
    vs[1][2].push_back(tmp);

    Student add[] =
    {
        {"Mary", "Jane"},
        {"Billy", "Bob"},
        {"Peggey", "Sue"}
    };

    int size = sizeof add / sizeof(Student);

    cout << "There are " << size << " students being added ...\n";

    for( int i = 0; i < size; ++ i )
         vs[1][2].push_back( add[i] );

    // show class vs[1][2] ...
    cout << "Class now has ... \n";
    for( size_t i = 0; i < vs[1][2].size(); ++i )
         cout << vs[1][2][i] << endl;
}
David W 131 Practically a Posting Shark

Hint ...
Try finding prime factors of each number,
then, gather up (multiply) all the common primes.

David W 131 Practically a Posting Shark

Just make a text editor and incorporate the interpreter.

What about the GUI?

( A text editer too ? Recall ... a cool project for just beginners :)

David W 131 Practically a Posting Shark

Just write your own with python like normal programmars do, it the pythonic approach.

Yep ... a really cool 'beginner' project :)

David W 131 Practically a Posting Shark

'IDLE' is always an easy ...
(and free) way to start coding in Python :)

David W 131 Practically a Posting Shark

You might also like to see this Python 3... example:
(that uses a function to loop until valid integer input)
(and that loops to ask user if more numbers to be input)
(and that demo's the use of a list 'generator')
(and that demo's the use of 'join')

# sumNumbers.py #

def takeInInt( msg ):
    loop = True
    while( loop ):
        try:
            i = int(input(msg))
            loop = False
        except( ValueError ):
            print( "Only integers valid here ... try again ..." )
    return i


nums = []
more = True
while( more ):
    num = takeInInt( "Enter next integer to sum: " )
    nums.append( num )
    more = ( input( "More (y/n) ?" ).upper() != 'N' )

lstNumAsStrsGen = list( str(x) for x in nums )
print( '+'.join(lstNumAsStrsGen), '=', sum(nums) )
David W 131 Practically a Posting Shark

Also @Avishek_1 ...

Please note that in standard C++ (and C)

it is int main ( NOT void main ) i.e. main returns an int

David W 131 Practically a Posting Shark

@Avishek_1

NOT good to use gets ... NOR to revert to old style C++ and mix up OP using stdio.h when OP was using C++ <iostream>

Also since OP using C++, best to use C++ string.

So ... would recommend something like this instead:

#include <iostream>
#include <sstream> // re. istringstream
#include <string>

using namespace std;



int main()
{
    cout <<"Enter a phrase: ";
    string line;
    getline( cin, line );

    istringstream iss( line ); // construct iss obj. from line

    // now parse and get word count and character count
    int chcount = 0;
    int wdcount = 0;
    string word;
    while( iss >> word )
    {
        ++wdcount;
        chcount += word.size();
    }

    // report ...
    cout << "\nWords = " << wdcount << endl;
    cout << "Characters = " << chcount << endl;

    cout << "\nPress 'Enter' to continue/exit ... ";
    cin.get();
    return 0;
}
David W 131 Practically a Posting Shark

Maybe ... they just have not yet learned about C++ "const correctness" ?

The use of const seems to be left ... till later ... for many students :)

David W 131 Practically a Posting Shark

'const' ...
in your examples ...

tells the compiler that the values in the array are NOT to be changed ... and the compiler will warn you then, if you / your program ... later ... tries to change any values in the array ...

Try compiling some code, that -> inside a function that has a const array passed in ... then attempts to change the values in the array ... and then SEE what your compiler reports back.

David W 131 Practically a Posting Shark

You need to turn them on, on your compiler ... to see them.

#include <windows.h>

//#include <stdio.h> // C usage style
#include <cstdio>    // C++ usage style

//#include <string.h>
include <cstring>

#include <cstdlib>
#include <ctime>

//#include <ctype.h>
#include <cctype>


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

using namespace std;
David W 131 Practically a Posting Shark

You have several compile errors ...

In line 81:

ISO C++ forbids variable length array 'boardWithPieces'

You could use a ...

vector < string > vecStr( size ); // calls constructor
// if you really need an 'array of strings'

You also have redundant and several C (not C++ type includes)

David W 131 Practically a Posting Shark

Python lends itself to jumping right in and start coding...

This example code below may give you some ideas about how to get started ...

# selectRobot.py #  # 2014-03-26 #

'''
The output will be like below:

    what type of robot application you like choose?
    a) assembly
    b) spot welding

Then let say the customer choose a or b, it will go to next question:

2.How much the load you expect for the robot to carry?
a) 0-2 kg
b) 0-5 kg

And so on ...

This is just a start ... need to continue ...
until finished choosing all attributes of the desired robot.

'''

menu1 = \
'''Please choose the type of robot application ?
    a) assembly
    b) spot welding
Please enter a or b    :  '''

menu2 = \
'''What is the max load for this robot?
    a) 0-5   kg
    b) 6-10  kg
    c) 11-15 kg
Please enter a, b or c :  '''

menu3 = \
'''What is the reach for this robot?
    a) 0-1 m
    b) 1-2 m
Please enter a or b    :  '''

menu4 = \
'''What is the mounting for this robot?
    a) floor
    b) wall
Please enter a or b    :  '''

def showMenuGetChoice( menu, low, high ):
    while True:
        reply = input( menu ).lower()
        if low <= reply and reply <= high:
            return reply
        else:
            print( "'", reply, "' was NOT in valid " \
                   'input range ', low, '..', high, sep = '' )

modelsStr = [] …
David W 131 Practically a Posting Shark

You seem to be making an easy thing hard ...

See this example of reading a 2D matrix from file, printing it back and then searching it to find a point ...

// myMatrixSearch.cpp //

/*

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

with the leading 2, indicating the number of rows
with the next 5, indicating the number of col's

you could read this into a matrix like this (using the STL vector container) ...

*/

const char* FNAME = "matrixData.txt";

#include <iostream>
#include <iomanip> // re. setw( )
#include <fstream>
#include <vector>

using namespace std;

ostream& operator << ( ostream& os, const vector< vector < int > >& v )
{
    for( size_t i = 0; i < v.size(); ++ i )
    {
        for( size_t j = 0; j < v[i].size(); ++ j )
        {
            os << ' ' << setw(8) << v[i][j];
        }
        os << endl;
    }
    return os;
}

struct Point
{
    int x, y;
    Point() :  x(-1), y(-1) {} // NOT found value
    Point( int a, int b ) :  x(a), y(b) {}
    void print() const
    {
        cout << x << ", " << y;
    }
} ;

Point find( const vector< vector < int > >& v, int val )
{
    for( size_t i = 0; i < v.size(); ++ i )
    {
        for( size_t j = 0; j < v[i].size(); ++ j )
        {
            if( val == v[i][j] ) return Point( i, j );
        }
    }
    // …
David W 131 Practically a Posting Shark

hint_prompt = hint_prompt.lower()

the string is converted to all lower case

David W 131 Practically a Posting Shark

Sometimes ... the obvious ... is alarmingly simple ... when you 'see' it :)

C arrays start at index 0, so next in, from front, has index 1,

and ... the last index is size-1 (if size > 0 ),

so next to last index is size-2 (if size > 1)

David W 131 Practically a Posting Shark

Do you 'see' the output here ... yes it prints '64' !

 cout << "\nThe following (new array_list) "
      << "is not from file\n\n";
SortedList x;
cout << "Inserting 64 ... ";
x.insert(64);
cout << "\nx.print(cout)... \n";
x.print( cout ); /// *** what does this do ? *** ///
cout << "\nx.size() = " << x.size();
cout << "\nErasing 64 ....";
x.erase(64);
cout << "\nx.print(cout)... \n";
x.print( cout );
cout << "\nx.size() = " << x.size();

But ... one should have really inserted several values and erased several values ... printing the list at each insert and erase ... to better check to see if the code is correct ... i.e. output was ... as desired ?

Try this:

cout << "\nThe following (new array_list) is not from file\n\n";

   SortedList x;
   cout << "Inserting 64 74 70 60... ";
   x.insert(64);
   x.insert(74);
   x.insert(70);
   x.insert(60);
   cout << "\nx.print(cout)... \n";
   x.print( cout );
   cout << "\nx.size() = " << x.size();

   cout << "\nErasing 64 ....";
   x.erase(64);
   cout << "\nx.print(cout)... \n";
   x.print( cout );
   cout << "\nx.size() = " << x.size();

   return 0;
David W 131 Practically a Posting Shark

Show the code you have so far ... and where you think you get stuck.