David W's Profile User Rating: ***--

Reputation: 277 Architect
Group:
Authors
Active Posts:
1,786 (0.84 per day)
Joined:
20-September 08
Profile Views:
20,605
Last Active:
User is offline Private
Currently:
Offline

Previous Fields

Country:
CA
OS Preference:
Windows
Favorite Browser:
FireFox
Favorite Processor:
Intel
Favorite Gaming Platform:
Who Cares
Your Car:
Chevrolet
Dream Kudos:
1225

Latest Visitors

Icon   David W is off-line ...

Posts I've Made

  1. In Topic: Find Id in Least to Greatest Order (Student Class)

    Posted 28 Jul 2014

    It is always good to use the C++ standard library functions where you need to sort and find elements in an array (or some STL container)


    Even if your design spec's call for coding you own sort and find functions, practice using the C++ library functions will help you gain a feel for good design.



    I would first tidy up the class code like this:

    // sortStudentsById.cpp //
    
    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <cctype> // re. tolower ...
    
    #include <algorithm> // re array sort, find ...
    
    using namespace std;
    
    const int SIZE_STUDENT_ARY = 5;
    
    class Student
    {
    public:
        // ctors...
        Student() : age(0), grade(0), id(0) {}
        Student( int age, int grade, int id, const string& name )
        : age(age), grade(grade), id(id), name(name) {}
        
    	void setAge( int age ) { this->age = age; }
    	void setGrade( int grade ) { this->grade = grade; }
    	void setId( int id ) { this->id = id ; }
    	void setName( const string& name ) { this->name = name ; }
    	
    	int getAge() const 	{ return age; }
    	int getGrade() const { return grade; }
    	int getId() const { return id; }
    	string getName() const { return name; }
    	
    	void print( ostream& os ) const
        {
    		os << left << setw(14) << name << ' '
               << setw(7) << id << ' '
               << setw(7) << grade << ' '
               << age << right;
    	}
    private:
    	int age;
    	int grade;
    	int id;
    	string name;
    
    	// to permit sorting by id's ... //
    	friend bool cmpById( const Student& a, const Student& b );
    	
    	// to permit finding by id and thus if id was used already ... //
    	friend bool operator == ( const Student& a, const Student& b );
    } ;
    
    



    These definitions could then come next ...


    // def'n of friend functions ...
    bool cmpById( const Student& a, const Student& b )
    {
        return a.id < b.id;
    }
    bool operator == ( const Student& a, const Student& b )
    {
        return a.id == b.id;
    }
    
    
    // def'n of overloaded << for Student objects ...
    ostream& operator << ( ostream& os, const Student& s )
    {
        s.print( os );
        return os;
    }
    



    Then ... to facilitate code reuse and ease of input (and output) ... these could be added in next ...

    // some utilities used here ..
    
    void printHeader()
    {
        cout << left << setw(14) << "NAME" << ' '
               << setw(7) << "ID" << ' '
               << setw(7) << "GRADE" << ' '
               << "AGE" << right << endl;
    }
    
    
    string toCapsOnAllFirstLetters( const string& strIn )
    {
        string str = strIn;
        int prev_was_space = 1;
        int len = str.size();
        for( int i = 0; i < len; ++ i )
        {
            if( prev_was_space )
                str[i] = std::toupper( str[i] );
            prev_was_space = isspace( str[i] );
        }
        return str;
    }
    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 char* msg )
    {
        int val;
        while( true )
        {
            cout << msg << flush;
            if( cin >> val && cin.get() == '\n' )
                break;
            else
            {
                cout << "Invalid input ... numbers only!\n";
                cin.clear(); // clear error flags
                cin.sync(); // 'flush' cin stream ...
            }
        }
        return val;
    }
    
    



    So now in main ... you can loop to fill up an array of Students

    (while there still is space)

    (and while more Students are requested to be input) ...

    See how you can use the library find function ... to ensure each id is unique.
    (Note: you need to have: #include <algorithm> to access the library 'find' and 'sort' functions.)


    // in main ... something like this logic flow works ok ...

    	Student students[SIZE_STUDENT_ARY];
    	int size = 0;
    	do
    	{
    		students[size].setName(
               toCapsOnAllFirstLetters( takeInString("Enter Name  : " )));
    		students[size].setAge( takeInValidInt(   "Enter Age   : " ));
    		students[size].setGrade( takeInValidInt( "Enter Grade : " ));
    		students[size].setId( takeInValidInt(    "Enter Id    : " ));
    		
    		if( find( students, students+size, students[size] ) != students+size ) // then found
    		{
    		    cout << "Sorry ... that ID is taken ... \n";
    		    continue;
    		}
    		
    		printHeader();
    		cout << students[size];
    		if( tolower(takeInChr( "  ...  Ok (y/n) ? " )) == 'y' )
                ++size;
    		else
        		cout << "Ok ... that student was NOT entered ...\n";
        		
    		if( size == SIZE_STUDENT_ARY )
    		{
    		    cout << "You have reached "
                     << SIZE_STUDENT_ARY
                     << ", the max space here!\n";
                 break;
    		}
    	}
    	while( more() );
    	
        printHeader();
    	for( int x=0; x < size; ++x )
    	{
    		students[x].print( cout );
    		cout << endl;
    	}
    
    	cout<< "Students ordered by ID ...  \n";
    	sort( students, students+size, cmpById );
    	printHeader();
    	for( int x=0; x < size; ++x )
    	{
    		cout << students[x] << endl; // using overloaded <<
    	}
    
    
    
  2. In Topic: parenthesis counter using stack

    Posted 27 Jul 2014

    An other approach is to use a 'table look up' logic ...

    Note how this method lends itself to readily expand the item-pairs to be examined to see if a balanced pair was used.


    const char BRACES[][2] = { "()", "[]", "{}", "<>" };
    const int NUM_BRACES = sizeof BRACES / sizeof *BRACES;
    
    /* return 0 if NOT found, or index+1 where found ... */
    int posBraces( char c, int type ) /* type: 0=open; 1=closed */
    {
        int i = 0;
        while( i < NUM_BRACES )
        {
            if( c == BRACES[i][type] ) return i+1;
            ++i;
        }
        /* if reach here... NOT found, so ... */
        return 0;
    }
    



    // then in main ...

            /* Ok ... now check the line that was just entered. */
            
            s.top = -1; /* initial top of stack to -1 */
            valid = TRUE;
            j = 0;
            
            while( exp[j] != '\0' && valid )
            {
                /* if in set of open braces ... */
                if( (pos = posBraces( exp[j], 0 )) )
                    push( &s, exp[j] );
    
                /* if in set of closed braces ... */
                else if( (pos = posBraces( exp[j], 1)) )
                {
                    if( empty( &s ) ) valid = FALSE;
                    else
                    {
                        if( BRACES[pos-1][0] == top( &s ) )
                            pop( &s );
                        else valid = FALSE;
                    }
                }
                ++j;
            }
    
        	/* Now test and report re. 'exit state' ... */
    
    



    Here is an other pair of utility type functions that you may like to add to your student coding 'tool-kit' ...

    char takeInChr( const char* msg )
    {
        char chr;
        fputs( msg, stdout ); fflush( stdout );
        chr = getchar();
        if( chr != '\n' )
            while( getchar() != '\n' ) ; /* flush stdin ... */
        return chr;
    }
    /* defaults to 'true'/'yes'/'1' unless 'n' or 'N' entered */
    int more()
    {
    	if( tolower( takeInChr( "More (y/n) ? " )) == 'n' )
            return 0;
    	/* else ... */
    	return 1;
    }
    



    Then you can easily code loops for more
    and readily get char type replies with a passed in prompt when-ever it's needed:

    // for example in main ...

    int main()
    {
       do
       (
          inputLineAndTestAndReportIfBalanced();
       }
       while( more() );
       return 0;
    }
    
  3. In Topic: parenthesis counter using stack

    Posted 27 Jul 2014

    Several things to fix:

    (1)

    int empty( struct Stack * ps )
    {
    	if( ps->top == -1 )
    		return True;
    	else
    		return False;
    }
    



    (2)

    void pop( struct Stack * ps )
    {
        if( !empty(ps) ) ps->top -= 1;
        else
        {
            printf( "Stack Underflow" );
            exit(1);
        }
    }
    



    (3)
    char top( struct Stack * ps )
    {
    	if( !empty( ps ) )
    		return  ps->items[ ps->top ]  ;
        /* else ... */
        printf( "Stack is Empty\n" );
        return 'X';
    }
    




    // in main ...
        // ...
    
        printf( "Enter a line to check: " ) ;
        fgets( exp, SIZE, stdin );
        p = strchr( exp, '\n' );
        if( p ) *p = '\0'; /* eliminate '\n' at end */
        else
        {
            printf( "The buffer size %d may not be large enough?\n", SIZE );
            while( getchar() != '\n' ) ; /* flush stdin ... */
        }
    
    
        j = 0;
        valid = True;
        while( exp[j] != '\0' && valid )
        {
            symb = exp[j];
            if( symb == '(' || symb == '{' || symb == '[' )
                push( &s, symb );
    
            if( symb == ')' || symb == '}' || symb == ']' )
            {
                if( empty( &s ) ) valid = False;
                else
                {
                    if
                    (
                        (symb == ')' && top(&s) == '(')
                        ||
                        (symb == '}' && top(&s) == '{')
                        ||
                        (symb == ']' && top(&s) == '[')
                    )
                        pop( &s );
                    else valid = False;
                }
                
            }
            ++j;
        }
    
    
    	/* test exit state ... and output results */
    		
    	if( empty(&s) ) /* print stuff */
    	else /* print stuff */
    
    
    	
    
    
    
  4. In Topic: Need Help with Loop to Get Input

    Posted 25 Jul 2014

    Since you sre using C++, why not use C++ strings?

    // pseudo code hints from @mojo666 embellished some :
    open file for output
    if opened ok
    {
       string str = "xxx"; // initial to any non-empty value //
       while( str.size() )
       {
          print "Enter some text: "
          getline( cin, str );
          if( str.size() )
             write str to file
       }
       close file
    }
    else print "Some error message ..."
    
    
  5. In Topic: Need help with small math program

    Posted 25 Jul 2014

    a = scanf("%d", &a);
    


    Hint:

    Look up scanf and see what it returns ???

My Information

Member Title:
DIC supporter
Age:
67 years old
Birthday:
June 29, 1947
Gender:
Location:
Toronto Ontario Canada
Interests:
The events that lead up to the soon return of Yeshua (Jesus) ... and being ready
Full Name:
David Wayne Zavitz
Programming Languages:
Basic
6502 Assembly
Comal
C++
HLA (High Level Assembly)
Pascal
C
Python
Sqlite3

Comments

Page 1 of 1
  1. Photo

    Invincible-99 Icon

    29 Jun 2012 - 06:10
    Oh, sorry!
    That link doesn't work.
    http://i48.tinypic.com/34qqrg3.jpg
  2. Photo

    Invincible-99 Icon

    29 Jun 2012 - 06:06
    Hi!
    [IMG]http://i48.tinypic.com/34qqrg3.jpg[/IMG]
  3. Photo

    Anarion Icon

    24 Jun 2012 - 13:44
    Regards to you, awesome friend! ;)
  4. Photo

    v0rtex Icon

    07 Jun 2012 - 03:04
    Thanks for the link! Why would u advise I look at HLA?
  5. Photo

    caleb123 Icon

    22 Jun 2010 - 19:37
    Would you like to be my website designing buddy? If you do, you can email me at cheryman22@yahoo.com
    You and I can give each other tips and answer question to make us both better at designing websites.
  6. Photo

    skyhawk133 Icon

    08 Jun 2010 - 09:43
    Great to have you David! Thanks for the kind comment.
  7. Photo

    xxxpriya Icon

    20 Feb 2010 - 21:25
    thanx a lot david
Page 1 of 1