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

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

Post the code you have tried so far.

David W 131 Practically a Posting Shark

You might like to see this for beginners in Python ...

http://developers-heaven.net/forum/index.php/topic,46.msg89.html#msg89

You will find that Python code is also very compact ...

A good (and it is also free online) tutorial/text is called 'Think Python'

http://en.wikibooks.org/wiki/Think_Python

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

Or ... (sorry to be a little late getting back) ... you might like to see a type of 'table look up' solution approach .. that can reduce code bulk and streamline logic flow ...

# examplePairsInList.py #

def takeInFlt( msg ):
    ok = False
    flt = 0.0
    while not ok:
        try:
            flt = float( input( msg ) )
            ok = True
        except:
            print( "Only numbers valid input here ..." )
    return flt

def shippingRate( shipWeight, rates, topRate ):
    for pair in rates:
        if shipWeight <= pair[0]:
            return pair[1]
    else:
        return topRate


if __name__ == '__main__':

    # ratePairs is a list of pairs : [ maxLbsAndUnder, rate ] #
    ratePairs = [ [2, 1.10], [6, 2.20], [10, 3.70] ]  
    maxRate = 3.80

    more  =  True
    while more:    
        weight = takeInFlt( 'Please enter the shipping lbs: ' )
        shipRate = shippingRate(weight, ratePairs, maxRate)
        print( 'Your shipping rate: ${:0.2f}'.format(shipRate) )
        print( 'Your shipping charges: ${:0.2f}'.\
               format(weight*shipRate) )

        more = ( input( 'More (y/n) ? ' ).lower() != 'n' )
David W 131 Practically a Posting Shark

Also ...

for examples like this:

int a = 1;
cout << "now a = " << (++(++a)) << endl; // two increments

// vs ...

int b = 1;
cout << "now b = " << (b += 2) << endl; // one addtion

// probably b is faster code
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

David, your suggestion i tried to use it, but the problem is this. The way the assignment is, it requires the user to enter one letter at a time. Upon entry, i am to store it into the array ([5] wide) as well as scan each entry to see if a duplicate exists in the array. If there is, i have to ask the user to try again. If it is a unique char, then i am to move on to the next memory location and do it all over again.

Ok ... so you can code a function ...

int alreadyExits( char testChr, const char* ary, int size )
{
   for( int i = 0; i < size; ++ i )
      if( ary[i] == testChr ) return 1;
   /* else if reach here ... */
   return 0;
}

And could use this ...

int takeInChr( const char* msg )
{
    char chr;
    printf( msg ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}

At top can have ...

/* ... */
#include <ctype.h> /* re. isalpha */
#define ARY_SIZE 5

Then in main ...

char ary[ARY_SIZE];
int size = 0;
printf( "You will now be asked to enter %d unique letters ...\n", ARY_SIZE );
while( size < ARY_SIZE )
{
   char c = takeInChr( "Enter a letter: " );
   if( isalpha( c ) …
new2code commented: thank you for this, it started to point me in the right direction. then my head exploded when i was trying to adapt your code to my needs and after 25 errors, i gave up. +0
David W 131 Practically a Posting Shark

You could (loop to) take in all 5 char's into a C string buffer at 'one go' ... using fgets and a sufficently (extra) large buffer

Then validate the 5 chars using ... these next 3 steps

  1. make sure 5 and only 5 chars long ... use strlen, include <string.h>

  2. use isalpha ... need to include <ctype.h> to make sure all char's are alpha ... as you traverse the C string

  3. make a copy into another C string buffer and sort (could use a bubble sort) and then traverse that sorted copy to see if each next char is always different from the previous

Note: you could code an 'isValid' function to handle all this.

/* prototype of a function to validate a C string ... */

/* returns 0 if NOT valid, otherwise return 1 */
int isValid( cont char* testStr );

/* Note: you MUST define before using the above */

Note 2: Recall that a C string is really just an array of char's, with an added terminal '\0' char ... to 'flag' the end.

David W 131 Practically a Posting Shark

Ok ...
firstly you had a typo, I think in your line 1 above:

I have found how to declare a two dimensional vector like below:

vector < vector < vector<int> > > myvector;

I think you meant to type (for just a 2D vector):

vector< vector< int > > myVec; // this is a 2D int vec //

What you had in that line 1 above, was actually a 3D int vector.

Would you like a little demo program that uses 2D (and then later, 3D) vectors?

Can you start the code?

David W 131 Practically a Posting Shark

No ... you can have as many D's as memory space permits.

If you wish to define some new objects, and encapsulate functions and data relevant to those objects, you could start out like this:

class Matrix
{
private:
   vector< vector< double > > grid;
public:
   //def's of ctors and member functions could come here
   // ...

} ;


class Cube
{
private:
   vector< vector< vector< double > > > box;
public:
   //def's of ctors and member functions could come here
   // ...

} ;

Or ... maybe some times you might prefer this ...

class Cube2
{
private:
   vector< Matrix > box;
public:
   //def's of ctors and member functions could come here
   // ...

} ;
David W 131 Practically a Posting Shark

@mike_2000_17 ... I thought your code above looked pretty cool ... and so thought that I would test it out, when I had a chance ... using a C++11 compiler.

I had a little trouble getting it to handle both kinds of errors ... (file open errors and running out of memory errors) ... as it was coded above.

This is what I came up with that actually did handle both kinds of errors the way expected ... and I thought you might like to see it.

// loadFromFile.cpp //

#include <iostream>
#include <vector>
#include <fstream>
#include <iterator>


const char* FNAME = "sample.dat"; // vs non file "sample2.txt";

// contents of test file: "sample.txt" :
/*
0 1 2 3 4 5 6 7 8 9
*/



int main()
{
    std::vector< double > data;

    try
    {
        std::ifstream fin( FNAME );

        if( fin )
            std::cout << FNAME << " opened ok ...\n";
        else
            fin.exceptions( std::ifstream::failbit );


        std::vector< double > data2;
        //data2.reserve( 10000000000 ); // to test 'a failed state'
        std::copy
        (
            std::istream_iterator< double >( fin ),
            std::istream_iterator< double >(),
            std::back_inserter( data2 )
        );

        data.swap( data2 );
    }
    catch( std::ios_base::failure &e )
    {
        std::cerr << "Catch block open file '" << FNAME
                  << "', had exception: '"
                  << e.what() << "'\n";
        return -1;
    }
    catch( std::exception& e )
    {
        std::cerr << "Catch block re. filling vector"
                  << ", had exception: '"
                  << e.what() << "'\n";
        return -2;
    }


    std::cout << "\nShowing contents of 'data' vector ... \n";
    for( auto e : …
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

Can you show your code?

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

You might try something like this ...

# compareTimes.py #

class MyTime: # 24 hour clock #

    def __init__(self, hrs=0, mins=0, secs=0):
        self.hours = hrs
        self.minutes = mins
        self.seconds = secs
        # normalize ... #
        if self.seconds >= 60:
            self.minutes += self.seconds//60
            self.seconds = self.seconds % 60
        if self.minutes >= 60:
            self.hours += self.minutes//60
            self.minutes = self.minutes % 60
        if self.hours >= 24:
            self.hours = self.hours % 24

    def get_sec(self):
        return (self.hours*60 + self.minutes) * 60 + self.seconds

    def __str__(self):
        return '{:02d}:{:02d}:{:02d}'.\
               format( self.hours, self.minutes, self.seconds )


def between( t1, t, t2 ):
    return t1.get_sec() <= t.get_sec() <= t2.get_sec()


t1 = MyTime( 9, 59, 59 )
print( 't1 =', t1 )

t2 = MyTime( 10, 0, 1 )
print( 't2 =', t2 )

t = MyTime( 10, 0, 0 )
print( 't =', t )

print( 'between( t2, t, t1 ) =', between( t2, t, t1 ) )
print( 'between( t1, t, t2 ) =', between( t1, t, t2 ) )
print( 'between( t, t1, t2 ) =', between( t, t1, t2 ) )

print( 'between( t, t, t ) =', between( t, t, t ) )
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

It appears

  • that you have an even number count in your lists of grades ...

and

  • you want the output to be formatted as a list of list pairs ... but with the name as the fist element in the outer list.

So ...

# nameGradePairsList.py #

grades = [ '4.5', '4.4', '3.9', '4.2', '3.8', '3.7' ]

grade_pair_lst = [ 'Sue Girl' ]
pair = []
for i, grd in enumerate(grades):
    if i % 2 == 0:
        pair.append( grd )
    else:
        pair.append( grd )
        grade_pair_lst.append( pair )
        pair = []

print( grade_pair_lst )
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

After you have the above working ... see added code and better comments here ... (but note the simpler and more symetric code demo'd above ... the 2nd example)

#include <iostream>
#include <iomanip> // re. setw
#include <fstream>

using namespace std;


void mergeFiles( ifstream& fin1, ifstream& fin2, ofstream& fout );

void showFile( const char* fname );


int main()
{
    ifstream fin1( "input1.txt" );
    ifstream fin2( "input2.txt" );
    ofstream fout( "output.txt" );

    mergeFiles( fin1, fin2, fout );

    fout.close(); // ensure flushed ... //

    showFile( "input1.txt" );
    showFile( "input2.txt" );
    showFile( "output.txt" );

    cout << "\nPress 'Enter' to continue/exit ... " << flush;
    cin.get();
    return 0;
}


void mergeFiles( ifstream& fin1, ifstream& fin2, ofstream& fout )
{
    int i1, i2, countIn = 0, countOut = 0;
    if( fin1 >> i1 ) ++ countIn;

    // Can firstly handle case of ...  if empty file 1 //
    if( fin1 ) // i.e. count == 1
    {
        // Then can handle case of ... if empty file 2 //
        if( fin2 >> i2 )
        {
            ++ countIn;
            while( fin1 && fin2 )
            {
                if( i1 <= i2 )
                {
                    fout << i1 << ' ';
                    ++countOut;
                    if( !(fin1 >> i1) )
                    {
                        fout << i2 << ' ';
                        ++countOut;
                        //break; // handled by while ... above //
                    }
                    else ++countIn;
                }
                else
                {
                    fout << i2 << ' ';
                    ++countOut;
                    if( !(fin2 >> i2) )
                    {
                        fout << i1 << ' ';
                        ++countOut;
                        //break; // handled by while ... above //
                    }
                    else ++countIn; …
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

Take a look at this little demo ...

#include <iostream>

// re comparing two arrays to see if hold 'equal' items ... //
#include <vector>
#include <algorithm> // re. vector sort ... //


using namespace std;


// print out a vector to ostream ...
ostream& operator << ( ostream& os, const vector< int >& v )
{
    vector< int >::const_iterator it;
    for( it = v.begin(); it != v.end(); ++it )
         os << ' ' << *it;
    return os;
}

// passed in arrays must be at least size 'size' ... //
bool equals( const int a[], const int b[], int size )
{
    vector< int > va( a, a+size ); // construct vector copy
    vector< int > vb( b, b+size ); // construct vector copy

    sort( va.begin(), va.end() );
    sort( vb.begin(), vb.end() );

    cout << "'a' sorted = " << va << endl;
    cout << "'b' sorted = " << vb << endl;

    return va == vb;
}

void pause()
{
    cout << "\nPress 'Enter' to continue ... " << flush;
    cin.get();
    cin.sync();
}


int main()
{
    int board[][5] =
    {
        {5,6,18,19,34},
        {5,25,28,29,40},
        {17,24,26,37,43},
        {1,8,14,34,42},
        {19,26,31,32,42},
        {5,14,27,35,40},
        {28,32,33,37,43},
        {2,13,18,41,45},
        {1,4,6,10,41}
    };
    int size = sizeof board / sizeof *board;
    cout << "size = " << size << endl; // 9 //



    // see if beginning row has same items as any other row

    bool redundant = false;
    for( int i = 1; i < size; ++i ) // start with i = 1 ... //
    {
        if( equals( board[0], …
David W 131 Practically a Posting Shark

If you took what I gave you above as a start ... you might have coded something like the following:

// countCharsWords.cpp //

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

using namespace std; 

// can easily change FNAME here ... //
const string FNAME = "Results.txt";
/*
Hello! Computer Science rocks! :) WOOHOOO!
*/

// can easily adjust char's to be included as PUNC ... here //
const string PUNC = ".?!,;";



int main() 
{ 
    ifstream fin( FNAME.c_str() );
    if( fin )
    {
        int numWords = 0, numChars = 0;
        string word;

        cout << fixed << setprecision(0); // show NO decimal

        // input each word until end of file ... //
        while( fin >> word )
        {
            ++numWords;
            int len = word.size();
            // if last char is in string PUNC ... //
            if( PUNC.find( word[len-1] ) != string::npos )
                word.erase( len-1 );
            numChars += word.size();
            // show words ...//
            cout << ' ' << left << setw( 15 ) << word;
        }
        fin.close();

        cout << "\n\nNumber of words was " << numWords
             << "\nNumber of letters was " << numChars
             << "\nAverage letters per word was "
             << double(numChars) / numWords << endl;
    }
    else
        cout << "\nThere was a problem opening file "
             << FNAME << endl;

    cout << "\nPress 'Enter' to continue/exit ... ";
    cin.get();
}
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

@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

This may get you started ...

// function to return true if char c 
// passed in is a vowel ...
// otherwise to return false
bool isVowel( char c )
{
    c = toupper(c);
    if( c == A' || c == 'E' || c == 'I' || 
        c =='O' || c == 'U' )
       return true;
     // else ...
    return false;
}

//int main()
//{
//   prompt for input ...
//   char c = cin.get();
//   if( isVowel( c ) ) cout << c << " is a vowel.";
//   else cout << c << " is NOT a vowel.";
//}
David W 131 Practically a Posting Shark

ok ...

could try (to start) something like...

fileName = "david_w.txt"

#intLevelNum intSecsLeft short text info re player
1            120         newbie 
1            30  
2            120
2            30
2            120
2            60
3            120
David W 131 Practically a Posting Shark

Since using C++, why not use C++ string and gain the ease of its use ?

Try something like this:

#include <iostream>
#include <string>

using namespace std;


void my_swap( char& a, char& b )
{
    char tmp = a;
    a = b;
    b = tmp;
}

// passed in string is validated to already contain '#' ....
void bubble_sort( string& s )
{
    bool swap;
    size_t size = s.find( '#' );
    do
    {
        swap = false;
        for( size_t d = 1; d < size; ++d )
        {
            if( s[d-1] > s[d] ) // For decreasing order use < //
            {
                my_swap( s[d-1], s[d] );
                swap = true;
            }
        }
        --size;
    }
    while( swap );
}



int main()
{
    string str;
    for( ; ; ) // loop forver until break ...
    {
        cout << "Enter a string to be sorted "
             << "up to the '#' char position in the string: \n";

        getline( cin, str );


        size_t i = str.find( '#' );
        if( i != string::npos ) break;

        // if reach here ...
        cout << "\nYour string needs to have a '#' char in it ... \n";
    }


    bubble_sort(str);

    cout << "Here is 'str' sorted up to '#' ...\n";
    cout << str << endl;

    cout << "\nPress 'Enter' to continue/exit ... " << flush;
    string dummy;
    getline( cin, dummy );
    return 0;
}
catastrophe2 commented: great code, but its a bit far from what i need. this code sorts almost any string, which is great! but it sorts it in alphabet i noticed and includes # at end of sort, which cant be there. more below... +1
David W 131 Practically a Posting Shark

What do you already know about a 4th power poly... ?

Can you (differentiate and) find the max (extreme points -> if the graph of y = ax^4 + bx^3 + cx^2 +dx + e opens down) ... or min ... if it opens up ?

From the extreme points ... and it it opens up or down ... can you see if it (touches or) crosses the x-axis ( ... so will have (1 or more) real roots then ... the rest imaginary <--always in pairs ,,,

niteshkumar.singh.9083 commented: YES i can +0
David W 131 Practically a Posting Shark

The coding problem that you seem to be posing is not a 'beginner type' problem, I would say ... So you should be able to post some code ... other wise ... the problem needs to be put off until you have some more coding skills.

And ... the coding spec's you give are not well defined ... Is your problem to simulate file storage ... but to use RAM and an array as the storage unit to access RAM?

David W 131 Practically a Posting Shark

But ...

C doesn't allow overloaded functions.

David W 131 Practically a Posting Shark

Because maybe he need to show example of goto statement, I don't care about reasons. Problem is solved and that's all I care about.

@Kristian_2
You do know that there is much more to coding, than ...

Problem is solved and that's all I care about.

Program (logic) flow ... using a standard structured coding style ... will make your code MUCH easier for you ... or some-else ... to maintain.

Some (complex) error handling may sometimes yield simpler code using a goto ... otherwise best to stick with 'best practice' usage of (a) standard coding style.

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

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

Using several functions ... a function for each task ...

could really help your program development ...

and help elucidate the logic flow.

// restaurant.cpp //


#include <iostream>
#include <string>

// to keep code portable ... best not to use this //
#include <windows.h> 


using namespace std;


const string HEADER = "TAPSI NI VIVIAN'S MENU";

struct Item
{
    string name;
    double price;
} ;

// putting data here, in an array of struct ... 
// makes your program more generic
// i.e. easier to revise ...
const Item MENU[] =
{
    { "Tapsilog", 80.00 }, { "Longsilog", 95.00 },
    { "Bulalo", 225.00 }, { "Sisig with Egg", 140.00 },
    { "Beef Mami", 50.00 }, { "Bottled Softdrinks", 25.00 },
    { "Canned Softdrink", 25.00 }, { "Minute Maid", 30.00 },
    { "Nestea", 20.00 }, { "Bottled watter", 15.00 }
} ;

const int NUM_CHOICES = sizeof MENU / sizeof *MENU;

// to keep code portable ... best not to use this //
void gotoxy(short x, short y)
{
    COORD pos = {x, y};
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}

void printMsgAt( const Item& itm, short x, short y )
{
    gotoxy( x, y );
    cout << itm.name << " P" << itm.price;
}

double getOrder( string& name )
{
    string msg, line( 65, '-' ); // construct string 65 '-'

    double amount = 0;
    for( ; ; ) // loop forvever until ... break or return ...
    {
        gotoxy( (60-HEADER.size())/2, 0 );
        cout << HEADER;

        short i;
        for( i = 0; i < …
Ancient Dragon commented: excellent advice +14
David W 131 Practically a Posting Shark

This example may give you some ideas how your above code could be re-coded using C++ idioms (and not Java idioms) ...

// insertSortedAryList.cpp //

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

using namespace std;


#define show 0 //set to 1 to turn ON 'showing...'//

const int MAX_ITEMS = 100; // need = at least 13 here ... //
const char* FNAME = "float.txt";
const char* FNAME_OUT = "float_sorted.txt";
/*
10.3 11.2 12.7 0.8 -3.2 11.7 -22.9 -1.1 9.9 -111.1 999 -999 0
*/


typedef float ItemType;
typedef ItemType* iter;
typedef const ItemType* const_iter;

class SortedList
{
public:

    SortedList() : length(0) {}

    int size() const  { return length; }

    void clear() { length = 0; }

    bool insert( const ItemType& x )
    {
        //cout << "length = " << length << endl;
        int i = 0;
        if( length < MAX_ITEMS )
        {
            if( length )
            {
                i = findInsertIndexBinSearch( x );
                if( i < length )
                {
                    // open up hole at index i
                    for( int hole = length; hole > i; --hole )
                    values[hole] = values[hole-1];
                }
            }
            values[i] = x;
        }
        else
        {
            cout << "\nList was FULL! NO room to insert!\n";
            return false;
        }
#if show
        cout << " at index[" << i << ']' << endl;
#endif
        ++length;
        return true;
    }

    bool erase( const ItemType& x )
    {
        bool wasDeleted = false;
        int i = foundAtIndexBinSearch( x );
        if( i >= 0 )
        {
            // copy down over item at index index i
            for( int j …
David W 131 Practically a Posting Shark

Once you get started coding in Python ... and get some feel for its (often very) simple coding style and power ... you may then want to DO many of your programming jobs in Python first ... and many of those, then ... may never get recoded in C++ :)

Here is a little demo C++

struct 'Contact' ...

with a way one might recode it in Python 3

that may help get you past 'go' ...

Firstly the C++ code ...

// Cpp_vs_Python.cpp //

#include <iostream>
#include <string>

using namespace std;

struct Contact
{
    string name;
    string phone;

    string toString() const
    {
        return name + ", " + phone;
    }
} ;


typedef Contact* iter;

int main()
{
    Contact book[] = { {"Sam", "1234567890"},
                       {"Bill", "2345678901"} };

    iter it,
         begin = book,
         end = book + (sizeof book / sizeof *book) ;

    cout << "Showing contacts in book ...\n";
    for( it = begin; it != end; ++it )
         cout << it->toString() << endl;

    cout << "Press 'Enter' to continue/exit ... " << flush;
    string dummy;
    getline( cin, dummy );
}

Ok ... now here is how one might recode this in Python 3
(Note how much shorter and simpler is the Python code.)

# Cpp_vs_Python.py #

class Contact:
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
    def __str__(self):
        return self.name + ', ' + self.phone

# get some data into a book (a list of Contact)

book = [ Contact("Sam", "1234567890"), Contact("Bill", "2345678901") …
David W 131 Practically a Posting Shark

I have to do a sorted list code according to some instructions.

What are the instructions?

Can you just use the STL list and the STL sort ?

or ...

Do you need to code your own class List and supply your own code to do a sort?

Even if you need to 'roll your own code' (bottom up) ...
it is often helpful to code the solution, firstly, using the STL ...

Then, when you have that all working well ... substitute in your own (pre-tested) list and sort.

Sorting a file, via reading it at first into a list, is conceptually very simple to code ... as this short demo of reading in a text file of 10 integers, indicates:

// listFromFileSorted/cpp //

#include <iostream>
#include <fstream>
#include <list>


using namespace std;

const char* FNAME = "myList.txt"; // example file to read and sort
/*
3 4 1 6 9 0 2 7 5 8
*/


void print( const list < int >& myLst )
{
    list < int > :: const_iterator it;
    for( it = myLst.begin(); it != myLst.end(); ++it )
        cout << *it << ' ';
}

int main()
{
    // read list from file
    ifstream fin( FNAME );
    if( fin )
    {
        list < int > myLst;
        int tmp;
        while( fin >> tmp )
            myLst.push_back( tmp );
        fin.close();

        cout << "Before sort ...\n";
        print( myLst );

        myLst.sort() ; // calls STL list sort

        cout << "\n\nAfter sort ...\n";
        print( myLst ); …
David W 131 Practically a Posting Shark

@Anicia ... if you do really wish help, on your Python coding problem, please start a new thread and show what work (and code) that you have so far ... in the direction of solving the problem.

David W 131 Practically a Posting Shark

You may like to see this revision ...

  1. that uses functions ...
  2. that takes in ('crash safe') string input
  3. that validates the input, in a loop, until valid
  4. that demos using the same function in different ways, via a 'flag' variable ... also, 'default values'
  5. that uses arrays ... so program can be made generic
  6. that uses a 'data struct' ... and an array of struct
    ... and '[i]' and '.' notations
  7. that uses Global constants so that the program can be easily revised to handle more than (array of size) 3
    etc...

See the added comments and note use of descriptive variable names ... to help 'self document' the code.

Enjoy ...

// top3Employees.cpp //

#include <iostream>
#include <string>
#include <sstream> // re. stringstream obj's
#include <cctype> // re. isdigit, toupper

using namespace std;


// can easily change these 2 GLOBAL constants, here, 
// to update whole program ...
const int MAX_NUM = 3; 
const string POSITIONS[] = { "1st", "2nd", "3rd" } ;

struct Employee
{
    string name;
    string data;
} ; // <- to tell compiler that the struct end is reached  //


// type 1: to be VALID, string MUST have 4 chars only, each a digit! 
// type 0: to be valid, sting must be NON empty ... (default type is 0)
bool isValid( const string& s, int type = 0 )
{
    if( type == 1 )
    {
        if( s.size() == 4 )
        {
            for( int i = 0; …
David W 131 Practically a Posting Shark

Just a variation on the theme... (for your enlightment and enjoyment) ...

Note the simple looping exit condition ...

The loop is exited when a cin error flag is raised by any invalid (here, any NON non-numeric) input ...

#include <iostream>
#include <iomanip> // re. formatting output ...
#include <string>

using namespace std;


int main()
{
    // set output to 2 decimal places ...
    cout << fixed << setprecision(2) ;

    const string prompt = "Enter the length of steel "
                          "bars bought (q to quit) : ";
    const int flat = 1000;
    const int min_len = 2;
    int length;

    // begin entry loop ... until 'q' ...
    // i.e. loop until any cin error here ... is reached
    while( cout << prompt << flush &&
           cin >> length && cin.get()  == '\n' )
    {
        double discFraction = 0;

        if( length >= 100 ) discFraction = .25;
        else if( length >= 80 ) discFraction = .20;
        else if( length >= 60 ) discFraction = .15;
        else if( length >= 40 ) discFraction = .10;
        else if( length >= 20 ) discFraction = .05;

        if( length >= min_len )
        {
            double total = flat * length;
            double disc = total*  discFraction;
            double discPercent = 100 * discFraction;

            cout << "\nTotal before discount :  $"
                 << setw(10) << total
                 << "\nDiscount              :  $"
                 << setw(10) << disc
                 << " (" << discPercent << "%)"
                 << "\nNet due               :  $"
                 << setw(10) << total - disc << endl;
        }
        else
            cout << "\nMinimun stock size is " << min_len;

        cout << "\n\nNext order ... \n\n";

    }

    cout << "\nQuitting ... " << flush;

    return 0;
}
Mart_webber commented: Thanks David +0
David W 131 Practically a Posting Shark

Oops ... I think you meant to use ...

int main()
{

   /* your code ... */

   return 0;

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

Nice :)

In C++, why not rather use C++ (safe) strings?

// in C++ ... why not use (safe) C++ string   ?

#include <iostream>
#include <string>
#include <queue>

struct Person
{
    const std::string name;
    int age;

    Person( const std::string& n="", int a=0 ): name(n), age(a) {}
    friend std::ostream& operator << ( std::ostream& os, const Person& p )
    {
        return os << p.name << ", age " << p.age;
    }
} ;


int main() 
{

    std::queue < Person > pq;
    pq.push( Person( "David", 66 ) );
    pq.push( Person( "John", 20 ) );

    Person front = pq.front();

    std::cout << "I am " << front << std::endl;

    return 0;
}
David W 131 Practically a Posting Shark

Ok ... you still need to clean it up a lot ...
I only edited enough so that I could compile it with an up to date C++ compiler ... and run it so it would not crash ...

Fixed up formatting a bit ... too ... so that you could BETTER see the progression of program flow ...

You need to use descriptive variable names.

In C++, the prefered way to declare your variables, is to declare them just before you use them ... and with just enough scope ONLY as you need!

//#include<iostream> // not used ... using ctdio
#include <cstdio>

//#include<conio.h>
//#include <windows.h>

using namespace std;

/*
void gotoxy( SHORT x, SHORT y )
{
    COORD coord = { x, y };
    SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), coord );
}
*/
void flushStdin()
{
    while( getchar() != '\n' ) ; // "flush" stdin ...
}

int Binary2Decimal()
{
    //gotoxy(1,17);
    printf("[BINARY TO DECIMAL CONVERSION]\n");

    //gotoxy(1,19);
    printf("Enter a Binary number: ");
    int b;
    scanf("%d", &b);
    flushStdin();

    printf("\n\n");

    int d=0, f=1;
    while(b>0)
    {
        if((b%10)==1)
        {
            d=d+f;
        }
        b=b/10;
        f=f*2;
    }
    printf("\nDecimal equivalent is: %d\n", d);

    return 0;

}

void Octal2Decimal()
{
    //gotoxy(1,17);
    printf("[OCTAL TO DECIMAL CONVERSION]\n");

    unsigned dec7,rem7,i7,sum7;
    //gotoxy(1,19);
    printf("Enter an Octal number: ");
    unsigned oct;
    scanf("%o", &oct);
    flushStdin();

    printf("\n\n");

    dec7=printf("%d", oct);

    rem7=dec7%8;
    sum7=sum7 + (i7*rem7);

    printf("\nDecimal equivalent is: %d\n", oct);
}

void Hexa2Decimal()
{
   // gotoxy(1,17);
    printf("[HEX TO DECIMAL CONVERSION]\n");


    unsigned number4,dec7,rem7,i7,sum7;
    //gotoxy(1,19);
    printf("Enter a Hex number: ");
    scanf("%x", &number4);
    flushStdin();

    printf("\n\n");

    dec7=printf("%d", number4);


    rem7=dec7%8;
    sum7=sum7 + (i7*rem7); …
ddanbe commented: helpfull +15
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

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