David W 131 Practically a Posting Shark

Need some help ASAP, so I emailed my teacher to verify my code and this is what he said:

"There is so much wrong, it is hard to know where to start.

Yes ... and the place to start is with an up-to-date C++ compiler and an up-to-date C++ course that uses present day C++ standard code.

You had a functioning library and driver and then went to add more levels. But, along the way, you got confused about terminology used in the new options. I thought we'd clarified that in our email discussion, but I see now I was wrong.

I do not have your non-standard version of C++ string...
So how can I help you with it?

But, there are things wrong on so many levels that I'm not sure what angle to approach. You have fundamental coding issues as well as high-level design issues.

Yes ... that seems a fair evaluation ... but your outdated course and compiler ... the root problem!

You try to define a type nickname for a vector of strings, but you haven't #include'd the vector library.

But ... ANY modern version of C++ has the STL

#include <vector> // this is how to do it in std C++

If you are using any non-standard C++ stuff ... recall you must always first include the definition(s) of any code ... before you try to call it.

David W 131 Practically a Posting Shark
/* parseOutDate.c */  /* 2014-03-03 */


/*
    I am trying to parse a date stored as an array of characters.
    I have a problem to parse the date with a loop ....
*/


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

#include <stdio.h>
#include <string.h> /* re. strlen, strncpy, strchr ... */
#include <ctype.h>  /* re. isdigit ... */

int more() /* defaults to 'yes'/'1' unless 'n' or 'N' entered */
{
    int reply;
    fputs( "More (y/n) ? ", stdout ); fflush( stdout );
    reply = getchar();
    if( reply != '\n' )
        while( getchar() != '\n' ); /* 'flush' stdin buffer */

    if( reply == 'n' || reply == 'N' ) return 0;
    /* else ... if reach here ... */
    return 1;
}

/* returns 'true' only if length is 8 and only all digits entered ... */
int validEntry( const char* s )
{
    int i,
        len = strlen(s);

    if( len != 8 )
    {
        printf( "\nExpecting 8 char's only ... try again.\n");
        return 0;
    }

    for( i = 0; i < len; ++i )
    if( !isdigit(s[i]) )
    {
        printf( "\nExpecting only digits ... try again.\n");
        return 0;
    }

    /* else ... if reach here ... */
    return 1;
}


int main()
{
    /* for entry "20141018" ... the date is 10/18/2014 */

    char year[4+1]; /* Recall, need 1 extra char for '\0' char at end */
    char month[2+1];
    char day[2+1];

    char buf[80];

    do
    {
        char* p;

        printf( "Enter a date (with entered format YYYYMMDD) :  " );
        fflush( stdin …
David W 131 Practically a Posting Shark

I am trying to parse a date stored as an array of characters. I have a problem (to parse the date) with a loop ...

This may help you get started ... note:

  1. input loop used
  2. use of functions
  3. input is validated
  4. fgets is used for input ... (and fgets is 'fixed')

Oops ...having a problem keeping code format here ... see next page

David W 131 Practically a Posting Shark

Recall when using

/* ... */

that ...

/* 
    code here does NOT GET COMPILED 
    into executable code  
*/

So you can add comments ...

or ...

comment OUT CODE blocks that you think you might use in an alternate version of the program ...

or ...

just delete ... in your final version ... all the code blocks that you are not using.

If you can not use C++ string in your program, and need a class String, you might like to see this freshly just fixed-up demo student version, (with 3 demo 'test.cpp' files ...that illustrate the use of that class String) ... at this next link:

David W 131 Practically a Posting Shark

You are way over-due to UPDATE to a modern C++ compiler ...

So many are free ... and UP-TO-DATE !!!

Or ...

since you are really using a lot of C code ...

you could recode it all in C, and repost fresh in the C forum here ...

(and, do not use conio.h, clrscr, gotoxy, etc... to keep your code portable),

with what errors you are getting ... where (what function ... what line) you think you are having your first coding problem?

David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

Do you know how to use Google ... or some other search site ... to do a search?

That is a 'basic tool' to master ... in learning computer programming ... these days.

Then ... trying out your own code ... and fixing it up to get it working the way that you want it to work ... code that YOU created and entered yourself ... top down and bottom up ... that is ALSO a basic !

David W 131 Practically a Posting Shark

When I just did a Google Search, on pure virtual function right now, this was at the top:

(You can do that too ... Yes ?)

When we add a pure virtual function to our class, we are effectively saying, “it is up to the derived classes to implement this function”.

Using a pure virtual function has two main consequences:

Firstly, any class with one or more pure virtual functions becomes an abstract base class, which means that it can not be instantiated! Consider what would happen if we could create an instance of Base:

int main()
{
    Base b; // pretend this was legal
    b.GetValue(); // what would this do?
}

Secondly, any derived class must define a body for this function, or that derived class will be considered an abstract base class as wel

David W 131 Practically a Posting Shark

You may have other errors ... best to post the whole section (or program).

/*
char year= "YYYY";
char month="MM";
char day= "DD";
*/

/*  But ... I suspect you want to have: */

const char* year= "YYYY";
const char* month="MM";
const char* day= "DD";
David W 131 Practically a Posting Shark

You are also using a C getchar() call with no C/C++ header <cstdio> to match.

But since ... coding in C++ ... use cin.get() instead.

David W 131 Practically a Posting Shark

Try this, popular with beginning students for ease of use ...

http://sourceforge.net/projects/orwelldevcpp/

David W 131 Practically a Posting Shark

Oops ... see below ...

David W 131 Practically a Posting Shark

Maybe this will give you some more ideas ...

// beginnerPayProgram.cpp //  // 2014-03-02 //


// Note the added loop, comments, keeping cin stream 'flushed as we go'
// and .. the demo of one simple way for validation, etc...



#include <iostream>
#include <iomanip> // re. setprecision( ), setw( ), etc ...
#include <cctype> // re. toupper ...

using namespace std;


int main()
{
    bool more = true;

    cout << setprecision(2) << fixed; // show 2 decimal places

    while( more ) // top while loop test ... loop until more = false
    {
        cout << "Enter hours worked :  ";
        double hoursWorked;
        if( cin >> hoursWorked )
        {
                cout << "Enter hourly rate  :  ";
                double hourlyRate;
                if( cin >> hourlyRate )
                {
                    cout << "Exempt (Y/N)       :  ";
                    char exempt ;
                    cin >> exempt;

                    exempt = toupper( exempt );
                    if( exempt != 'Y' && exempt != 'N' )
                    {
                        cout << "You did not enter 'Y' or 'N' ... \n";
                        continue; // from top 'while loop test' *NOW*
                    }

                    // Ok ... all good so far ... but good to ...
                    // 'flush' cin stream /  'eat' the '\n' char left,
                    // that IS still there at the end of the cin stream

                    while( cin.get() != '\n' ) ; // exits when eats '\n' char left above

                    // Now ... calculate and report

                    cout << "\nGross wages        =  $" << setw( 8 )
                         << hoursWorked * hourlyRate << endl;

                    if( exempt == 'Y' )
                        cout << "NO TAXES …
David W 131 Practically a Posting Shark

Hope 'your new web site' bristols with bright business. Are you thinking of franchises yet ... like one near Toronto Ontario Canada area :)

Best regards,

David W Zavitz

P.S. I noticed your student programming (C/C++, etc.) help site ... some years ago ... but it was only last summer that I thought about becomming a contributer ... especially after I read something about, how the changes with Google search engine, really ... 'hit your hits' hard. I also ... used to be always (within 2 or 3 Google links from) the top of Google page one ... if the key words ... Beginnning Computer Programming ... were entered. But just now ... Google shows only one (indirect) link ... and it's now on Google page ten ... but I'm still at the top of page one ... on Bing :)

David W 131 Practically a Posting Shark

Also ... you may like to see this (revised) ...

class String:

David W 131 Practically a Posting Shark

You may like to see this version using fixedFgets ...

to see another way to handle input problems in C.

/* demo 'fixedFgets' and 'keeping flushed' the stdin stream... */

#include <stdio.h>
/* #include <stdlib.h> */
#include <string.h>
#include <ctype.h>

#define MAX 1024
#define FALSE 0
#define TRUE  1

int vowel_count( const char* );
int conso_count( const char* );
void to_all_lower( char* );
void to_all_upper( char* );


/* example of a way to fix fgets TWO very annoying problems   */
char* fixedFgets( char* s, size_t bufSize, FILE* fin )
{
    if( fgets( s, bufSize, fin ) )
    {
        char *p = strchr( s, '\n' ),
             c ;
        if( p ) *p = 0; /* strip off '\n' at end ... iF it exists */
        else while( (c = fgetc( fin )) != '\n'  &&  c != EOF ) ; /* flush... */
        return s;
    }
    /*  else ... if reach here ... */
    return NULL;
}

int showMenu_getChoice()
{
    int choice;
    printf( "A)  Count the vowels in the string\n" );
    printf( "B)  Count the consonants in the string\n" );
    printf( "C)  Convert to all uppercase\n" );
    printf( "D)  Convert to all lowercase\n" );
    printf( "E)  Display the current string\n" );
    printf( "F)  Enter a new string\n\n" );

    printf( "X)  Exit the program\n" );

    printf( "\nEnter your choice: " );

    choice = toupper( getchar() );
    while( getchar() != '\n' ) ; /* 'flush' stdin as you go ... */

    return choice;
}



int main()
{
    char data[MAX];
    int flag = …
David W 131 Practically a Posting Shark

I had thought, (maybe wrongly, it seems now), that you had wanted to multiply Matrix A ... by a Matrix B ... where both were input as one long vector ... and the product Matrix was also returned as one long vector.

David W 131 Practically a Posting Shark

Did you realize that you are taking in your 3 data elements twice?

And that the 2nd 'take in' set of data ... over-write the first?

Also ... do you realize that in math:

For any value a,

( a - 0.18*a ) 
= 
a * (1 - 0.18) 
= 
a * 0.82 

So your calculation can be a little more efficently coded ... yes?

David W 131 Practically a Posting Shark

A common student 'overload' ...

is, overloading operator <<

to output the data in a (student) data set ...

See the following:

Data file: myData.txt

1 20000101 Jane Doe
4 19711203 Hannah Mariam Johnston
2 19900303 Joe
3 19990324 James Harry Robinson

Program:

// simpleVecStructFromFile.cpp // 2013-03-23 //

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

#include <cctype> // re. isspace

using namespace std;

const string FNAME = "myData.txt";

struct Student
{
    int id;
    int dob;
    string name;

    // default ctor
    Student() : id(0), dob(0) {}

    // def'n of overloaded << for Student obj's ...
    friend ostream& operator << ( ostream& os, const Student& s )
    {
        return os << s.id << ", " << s.dob << ", " << s.name;
    }
} ;

// show whole vector v ... uses above def'n of overloaded << for Student obj  
ostream& operator << ( ostream& os, const vector < Student >& v )
{
    int i= 0, len = v.size();
    for( ; i < len ; ++ i )
        os << v[i] << endl;
    return os;
}

void ltrim( string& s )
{
    int i = 0, len = s.size();
    while( i < len && isspace(s[i]) ) ++i;
    s.erase( 0, i );
}



int main()
{

    ifstream fin( FNAME.c_str( ));
    if( fin )
    {
        vector < Student > v;          // construct empty Student vector v
        string line;
        while( getline( fin, line ) ) // get this whole line & 'eat' '\n' at end
        {
            istringstream iss( …
David W 131 Practically a Posting Shark

To the OP:

Have you thought about doing some assembly coding?

HLA (High Level Assembly by Randy Hyde) is a great way to start to get a feel for what is going on under the hood ... and it 'leverages' your C/C++ coding skills to let you get to a fast-track start in writing useful code.

Edit: Oops ... that was an old post that shyrin seems to have 'fallen in to' ...

I see that I 'fell in' ... too :(

David W 131 Practically a Posting Shark

A quick Google turned up this ... (for starters)

http://www.cprogramming.com/tutorial/function-pointers.html

...

Callback Functions
Another use for function pointers is setting up "listener" or "callback" functions that are invoked when a particular event happens. The function is called, and this notifies your code that something of interest has taken place.

...

You might want to start with function pointers ... like you may wish to use when passing in a different compare function to a library sort ... to sort on different fields, etc... ?

David W 131 Practically a Posting Shark

Perhaps the OP means ...

'under what star' was that DOB ?

If so ... then the programmer needs a program that has a table of 'Stars' and dates (or date ranges) ...

The program can loop to ask the user to input a (VALID) date of birth ...

then ... code a look up of that DOB in the table

then ... report

then ask for another 'star / dob' combination to find ... or quit.

Now ... just code a working shell program (with comments like the above) ... and the OP will be 'on target' ... with ... step 1 DONE!!!

Can you code a 'Hello World!' program in C++ ?

Can you code a loop that asks for more?

Can you prompt for C++ string user input and take in a string in a C++ string (variable)?

Can you do a TABLE LOOK UP ... to see if a string is in a table?

Can you report the matching item in the table, if lookup was successful?

These are tasks needed above.

To see some of these tasks demonstrated, you could check here:

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

David W 131 Practically a Posting Shark

This (C++) lab will help you practice with C-strings and libraries. Function overloading (in C++) might come in handy, as well.

Two useful functions that are not provided in the standard library (but are with standard C++ string) are find a character in a string and find a substring in a string.

NOTE! These are also provided in C for C strings:

char* p = strchr( str, ch ); // find char ch in str
char* q = strstr( str, findStr ); // findStr in str

So it seems you are to write a 'wrapper' for your class xString that uses a dynamic C string inside the class to hold C strings.

So ... your code can just use the two above C provided functions ... (or you can 'Roll Your Own' - Which IS generally NOT advised!)

If you look at the class String example that I provided for you on an earlier post, you will see there, these examples:

int get_index( char charToFind ); // returns index or -1;
int get_index( const String& strToFind ); // returns index or -1 ... case specific
int get_index_ignore_case( const String& strToFind );

David W 131 Practically a Posting Shark

Also ... you will have much more joy in your coding in C when you find some regular ways to easily handle the problem of char's left in the input stream ...

After input ... often left are char's like the '\n' char at the end of a line.

These 'left over' char's ARE a BIG problem for new coders ... so the sooner you see the easy fixes, the sooner you will enjoy coding in C :)

(These 'left-over' char's ... will mess-up you next attempt to enter anything ... since those 'left-over' char's are ALL-READY there ... in the input stream, before you enter anything else ... they will be taken for the next input.)

When inputing (SINGLE word - NO spaces) strings, using scanf, you need to specify a max field width ... (so that you do not overflow the string size into other memory and crash the program or something?)

If spaces may occur in your input strings, use fgets to get the whole line ... and then fix that input by stripping off the '\n' char at the end ... or flushing the input stream if the buffer (size) did NOT hold the whole line ... (if that is what you want.)

Also, when passing struct's that hold more bytes than the bytes in the address size you are using ... pass the address (pass by reference ... NOT by value) ... to save making a copy of ALL that data in the struct ... …

Ancient Dragon commented: agree +14
David W 131 Practically a Posting Shark

Further to the above by Ancient Dragon ...

you may like to recall that C strings are pointers to ...

(a '\0' terminated block of)

char ...

(i.e. addresses)

So ... do you wish to ask ...

if the addresses are the same?

Probably not ... most of the time :)

David W 131 Practically a Posting Shark

This example may be helpful ...

/* matrixMult.c */

/* each matrix here is stored as one long vector with row*col length */


#include <stdio.h>
#include <stdlib.h> /* re. malloc ... */
#include <ctype.h> /* re. tolower ... */


void myAssert( int condition, const char text[] )
{
    if( !condition )
    {
        fprintf(stderr, "%s\n", text );
        fputs( "Press 'Enter' to exit program ... ", stderr );
        getchar();
        exit(1);
    }
}

int* getNewIntArrayMemory( int size )
{
    int* ary = malloc( size * sizeof( int ) );
    myAssert( (ary != NULL), "\nERROR ... malloc failed in"
                             " 'getNewIntArrayMemory' \n" );
    return ary;
}
int* takeInArrayMatrix( int r, int c )
{
    int i, j;
    int* m = getNewIntArrayMemory( r * c );

    printf( "Enter the %d elements of this matrix\n", r * c );
    for(  i = 0 ; i < r ; i++ )
        for( j = 0 ; j < c ; j++ )
        {
            printf( "a[%d] = ", i*c + j );
            scanf("%d", &m[i*c + j]);
        }
    return m;
}
void print( const int* m, int rows, int cols )
{
    int i, j;
    for ( i = 0 ; i < rows ; ++i )
    {
        for( j = 0 ; j < cols ; ++j ) printf( "%3d ", m[i*cols + j] );
        putchar( '\n' );
    }
}


int takeInChar( const char* msg )
{
    int reply;
    fputs( msg, stdout ); fflush( stdout );
    reply = getchar();
    if( reply != '\n' )
        while( getchar() != …
David W 131 Practically a Posting Shark

oops ... see below

David W 131 Practically a Posting Shark

This parsing could be a breeze if you use C++ string and stringstream to parse ... using :

istringstream iss( cppStrToParse ); // construct iss

getline( iss, cppStrMth, '/' ); // to get month and then

getline( iss, cppStrDay, '/' ); // to get day and then

getline( iss, cppStrYr ); // to get the year at the end

If you need to use C string types ... I have a readWord.h with readWord that will parse a C string line into (dynamic C string) words ... with your choice of delimiters.

/* readWord.h */ /* this ver 2013-07-11 */

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

/*
    Safe string data entry from file or keyboard ...
    BUT ... free new memory when done with it!
    Don't forget that C strings are pointers to a block of char,
    with a '\0' char at the terminal end ... Call like this:

    char* word = readWord(stdin, 31, "\n\t ,.;:", &lastChr);//note delimiter str

    or ...

    while((word = readWord(FILEp, startChunkSize, delimiterStr, &lastCharRead)))
    {
        // do stuff ...
    }

    Note 1: select your initial word chunk size to minimize calls to realloc
    Note 2: address of last char passed in/out so can flush stdin or file line
*/
David W 131 Practically a Posting Shark

You may get some ideas from the example below ...
(that uses C++ STL stack and ...)

Recall that a stack is FILO <-> First In Last Out.

// testPalindromeAllInOne.cpp //

#ifndef PALINDROM_H
#define PALINDROM_H

/**
 * @file Palindrome.h
 */
#include <string>
#include <cctype>

#include <algorithm>

//#include "ArrayStack.h"

#include <stack>


using namespace std;


class Palindrome
{
private:
   /**
    * stores the letters in the string while it is being evaluated
    * to determine if it is a palindrome
    */
   stack < char > letters;

   /**
    * original phrase to evaluate to determine if it is a palindrome
    */
   string phrase;

public:
   /**
    * Default constructor. Initializes expression to an empty string.
    */
   Palindrome ()
   {
      phrase = "";
   }


   /**
    * Overloaded constructor that initializes the phrase.
    * @param - newPhrase - original phrase tested to determine if it is a
    *          palindrome
    */
   Palindrome (string newPhrase)
   {
      phrase = newPhrase;
   }

   /**
    * Evaluates the phrase to determine if it is a palindrome. Uses
    * a stack to reverse the order of the letters in the phrase and
    * to determine if the original phrase is a palindrome. A palindrome
    * is a sequence of letters that reads the same forward and backward;
    * however, all spaces and punctuation are ignored.
    * @return isPalindrome - true if phrase is a palindrome; false
    *                        otherwise
    * @param reversePhrase - orginal phrase in reverse order, including
    *                        all puncutation and spaces
    */
   bool evalPalindrome (string& reversePhrase);
} ;

#endif …
David W 131 Practically a Posting Shark

Since you are coding ALL in C, why not start fresh in the C forum ... I think I have some ideas that you may find useful.

David W 131 Practically a Posting Shark

Congratulations ... you got it working.

But ...

I hope you have the right solution, because that is not how I understood your coding problem ... (see above.)

Ask the user to enter on the keyboard a starting value nstart of a positive integer number n. CHECK

Ask the user to enter on the keyboard the ending value nstop of n. CHECK

Ask the user to enter on the keyboard the increment nstep in n from one value to the next. CHECK

The program is then to display on the console a table consisting of two columns, one displaying values of n starting at n1 ? (nstart?) and the other displaying the corresponding zNumber (what is a zNumber) values. Make sure that your display includes suitable headers for the two columns. ??? maybe NOT CHECK ??? depending on what is a zNumber ... and what the first column is to be ???

Note, below, the clean-ups and comments

and NEW heading on the output ...

to try to show you what your code was actually doing:

/* edited version */

#include <stdio.h>
#include <math.h>


int main()
{
    int n, nstart, nstop, nstep; /*  zNum; */ /*  NOT used here */

    printf("Please enter a positive integer for nstart : ");
    scanf("%d", &nstart);

    printf("Please enter a positive integer for nstop  : ");
    scanf("%d", &nstop);

    printf("Please enter a positive integer for nstep  : ");
    scanf("%d", &nstep);

    printf("Start\t\tStop\t\tSumOfCubes\n");
    printf("-----\t\t----\t\t----------\n");

    n = nstart; /* start with the given nstart value */

    while( …
David W 131 Practically a Posting Shark

If what you want do, is to sum a series of numbers cubed, you can very simply just,

for each next real number x,

add

x*x*x to the sum.

Note: the sum was set to an inital value of 0.0

You can show the ...

------     -----      --------------------
Next x     x*x*x      Running Sum of Cubes
------     -----      --------------------

in a table format as you go ...

The example code above, outputs a similar table.

Note that the prototype for pow is:

double pow (double base, double exponent);

In C, if you pass in an int type value for base and/or exponent, each int type will be 'promoted' to type double ... inside the pow function ... since the numbers are passed in by value.

David W 131 Practically a Posting Shark

If this is another problem ...

(i.e. a new assignment you are working on),

please start a new thread, and state clearly what the problem is, what your quide lines are, if any,

(for example: use C strings only? sort a certain type of formated file ? ... etc.),

and show what code you have ... and where you are having problems coding ... or not getting the expected results.

David W 131 Practically a Posting Shark

That help was so thoughtful, when half sleeping, it must be awesome when awake :)

David W 131 Practically a Posting Shark

I think "Schol-R-LEA" meant to type:

using namespace std; // :)

It it always good, (especially for beginner coders), to start out with a working shell C++ program like 'Hello World' ... that compiles and gives the exact expected output ...

Then ... add a few lines ... (or a function, etc) ... and re-compile and test the output ... and fix till it works.

If there is a bug in the added new block of code, you will know 'where to look' ... just look in that added (small) block of code ... most probably :)

Always keep a copy of your last working 'step'. Then, if you can-not find the bug in your next stage of added code, you can always go back to a working program and add a smaller (compiling / working?) block of code.

// use comments to document what you want to do 
// at each stage
// this function prints out the values in
// an int array called 'ary' with size 'size'
void print( const int ary[], int size )
{
   for( int i = 0; i < size; ++i ) cout << ary[i] << ' ';
   // print newline at end
   cout << endl;
}
David W 131 Practically a Posting Shark

I do not have access to your string type ... (nor do I care to have access to it.)

I sent you a link to a string class ... so that we can both work 'on the same basis' ... I am willing to help you, if I can ... with that.

It IS really way over-due for you to get updated to the present version of a C++ compiler ... (and several are free !!!)

If you want to use C type (dynamic) strings ... I have a free student C utilities library that easily handles that (with utilities for Cvec and Clist with insert and merge sorts, etc...) :

#include "readLine.h"

/* readLine.h */ /* this version: 2013-07-10 */

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

/*
Safe string data entry from file ... to replace gets and fgets
BUT free new memory ... when done! Don't forget that C strings are
pointers to a block of char, with a '\0' char at the terminal end ...

Call like this:

    char* line = readLine( stdin );

    or ...

    while( (line = readLine( FILEp )) )
    {
        // process line ...
    }
*/



#include "readWord.h"

/* readWord.h */ /* this ver 2013-07-11 */

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

/*
Safe string data entry from file or keyboard ...
BUT ... free new memory when done with it!
Don't forget that C strings are pointers to a block of char,
with a '\0' char at the terminal …
David W 131 Practically a Posting Shark

re. if you want to add a sort function to sort by
1. names
or
2. points

to sort a C++ list, just call the STL sort provided

list < City > c;
// after taking in cities, c holds list of cities

// make sure you have already defined, 
// your GLOBAL desired compare function
bool cmpNames( const City& c1, const City& c2 )
{
   // to sort on name field ...
   return c1.get_city_name() < c2.get_city_name(); 
}

...

//call list sort
c.sort( cmpNames );

And ... of course ... update your MENU to include the added sort choice(s).

David W 131 Practically a Posting Shark
  • re. class City_list version ...

See how easy it is to get to that ... (working from the example already given) ...

// distanceTwoCitiesList.cpp //

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

//#include <vector> // replaced here by list to make deletes fast and easy //
#include <list>
#include <cmath>
//#include <cctype>

using namespace std;


const string MENU = "Please choose from the following options below: \n"
                    "1. Add a city \n"
                    "2. Calculate distance between cities \n"
                    "3. Print all cities \n"
                    "4. Delete a city \n"
                    "5. Quit \n";

class Point
{
public:
    Point(void);

/*
    Point(double new_x, double new_y);
    Point(const Point & p);

    void set_x(double new_x) { x = new_x; }
    void set_y(double new_y) { y = new_y; }

    double get_x(void) const { return x; }
    double get_y(void) const { return y; }
*/
    void takeIn(void);

    double distance (const Point & other) const;

private:
    double x, y;
    friend ostream& operator << ( ostream& os, const Point& p )
    {
        return os << p.x << ", " << p.y;
    }
} ;

Point::Point(void)
{
    x = y = 0.0;
}
/*
Point::Point(double new_x, double new_y)
{
    x = new_x;
    y = new_y;
}
Point::Point(const Point & p)
{
    x = p.x;
    y = p.y;
}
*/
void Point::takeIn(void)
{
    char comma;
    for( ; ; )
    {
        cout << "Enter point x,y (enter comma also) :  ";
        cin >> x >> comma >> y;
        if( cin.good() ) break;
        cin.clear();
        cin.sync();
        cout << "\b***Only NUMBERS valid*** here ... Try again!\n"; …
David W 131 Practically a Posting Shark
  1. re.

    int takeInChar( const string& msg )
    {
        cout << msg << flush;
        string reply;
        getline( cin, reply );
        if( reply.size() )
            return reply[0];
        // else ... if did NOT return above ... then
        return 0;
    }
    

This is a (slightly more) efficent code than:

   int takeInChar( const string& msg )
    {
        cout << msg << flush;
        string reply;
        getline( cin, reply );
        if( reply.size() )
            return reply[0];
        else return 0;
    }
David W 131 Practically a Posting Shark

You forgot to ...

Show us where you are having trouble(s) ...

David W 131 Practically a Posting Shark

... only a few ?

Coding can really be fun ... once one knows what to do :)

It may take quit a while ... for that to happen !

Writing lots of code and trying it out until one sees what each part does ... that's the way to gain confidence in your coding.

You might like to see the (edited) code below:

/*  loopToSumCubes.c */

/*
    Ask the user to enter on the keyboard a starting value nstart
    of a positive integer number n.

    Ask the user to enter on the keyboard the ending value nstop of n.

    Ask the user to enter on the keyboard the increment nstep in n
    from one value to the next.

    The program is then to display on the console a table consisting
    of two columns, one displaying values of n starting at n1
    and the other displaying the corresponding zNumber values ( sums ? )

    where ... double zNumber = pow( double_n, double_i );

    Make sure that your display includes suitable headers for the
    two columns.

*/

#include <stdio.h>
#include <math.h>



int main()
{
    int n, nstart = 1, nstop = 10, nstep = 1;

    double sum = 0.0;

    int bad1, bad2, bad3;
    do
    {
        bad1 = bad2 = bad3 = 0; /* initial all to be NOT bad ... */

        printf("Please enter a value of a positive integer nstart: ");
        scanf("%d", &nstart);
        if( nstart < 1 ) bad1 = 1;

        printf("Please enter a value of a positive integer nstop: …
David W 131 Practically a Posting Shark

So ... are you saying that you need to keep asking for more cents to be input in a loop ... until the user indicates that they are done ?

And each time, show the dollar and the cents totals so far?

Since you do not wish to use pass by reference ...
you could return a struct to hold dollars and cents
and update the totals outside the function each loop,
as per the following C++ struct example ...

// centsToDollars2.cpp //

#include <iostream>

using namespace std;

struct Change
{
    int dollars;
    int cents;

    // default constructor sets to zero (optional, since not needed here)
    Change() : dollars(0), cents(0) {}

} ; // don't forget this ; to indicate the struct is done!


// Function Prototypes.
Change NormalizeMoney( int );



int main()
{
    int tot_dollars= 0; // totals initialed to 0
    int tot_cents=0;    // totals ...
    int count=0;        // totals ...

    int cents = -1;
    for( ; ; ) // an example of a C/C++ forever loop ... until break
    {
        cout << "(Enter 0 when finished.)\n";
        cout << "Enter the amount of cents you want to add: ";

        if( cin >> cents && cents >= 0 &&  cin.get() == '\n' )
        {
            if( !cents ) break;

            // OK ... we have cents ... so can ...

            Change tmp = NormalizeMoney( cents );

            tot_dollars += tmp.dollars;
            tot_cents += tmp.cents;

            ++ count;

            cout << "After " << count << " entries, you have accumlated "
                 << …
David W 131 Practically a Posting Shark

That is not a map of M -> v ...

v is all set to zero there,

( but it shows the general idea,
if zero is replaced by M[i][j] )

Now show your code for ...

M1*M2 => M3

with row & column checking

and the appropriate size for M3

David W 131 Practically a Posting Shark

Can you show your map of a 'n by m' Matrix to a vector of length n*m ?

And then do regular matrix multipliction ( with appropriate size checks) ...

Then ... M1*M2 => M3

should map to ...

vm1*vm2 => vm3

David W 131 Practically a Posting Shark

Just pull the respect code parts out ...

and put them into a ...

.h file (with appropriate 'guards')

and a ...

.cpp file that includes the .h file

Then include the .h file in your main (test program)

David W 131 Practically a Posting Shark

Is what you are trying to do is to transform a vector?

i.e. M1*v1 => v2
i.e. Matrix1 times vector1 = vector2 ?

David W 131 Practically a Posting Shark

Just noticed this post, that seems to go with your other post ...

Again, it would seem best to use the C++ STL stack (or list) to hold the char's

This could serve as a 'quick/cheap' test program ...
(and your eval... section, could be vastly cleaned-up/simpified.)

// testPalindrome.cpp //

#include <iostream>

// quick/cheap test method ... //

#include "palindrome.cpp"
// includes all the below ...
/*
#include "palindrome.h"

#include <string>
#include <cctype>

#include <algorithm>

//#include "ArrayStack.h"

#include <stack>

using namespace std;
*/



int main()
{
    string test = "a b c d e f g f edcba", revStr;

    cout << test << endl;

    Palindrome p( test ); // construct ...

    cout << ( p.evalPalindrome( revStr ) ? "true" : "false" )  << endl;

    cout << revStr << endl;

    cout << "Press 'Enter' to continue/exit ... " << flush;
    cin.get();
}
David W 131 Practically a Posting Shark

Why are you using ...

"ArrayStack.h"

It would seem much better to use the C++ STL stack (or list) to hold each char ... then we can 'talk' ...

Also ... a test program ... and your results with your input vs what you expect to get.