David W 131 Practically a Posting Shark

@tinstaafl ... a Dani Virtuoso indeed ... very well designed and developed ... and demos the efficent code that can be often obtained by the use of tables.

This variant, with validation of user input, may want some more testing ... but it seems to do the job of limiting input to a valid range ... well maximizing the range of numbers that can be converted ... limited only by the number of bits in an unsigned long.

It first prints out a table ... a table of max digits and max (string) value that can be obtained ... if limited by the intermediary use for storage in an unsigned long (commonly these days ... 32 bits)

// baseConversion_tinstaafl.cpp //

#include <iostream>
#include <iomanip>
#include <sstream>
#include <cctype> // re. toupper
#include <climits>

using namespace std;

typedef unsigned long UL;

const unsigned int NUM_BITS  = sizeof(UL) * 8;

const UL MAX_UL = ULONG_MAX;

// to track max values of other base numbers
// that fit into a UL ...
struct Values
{
    string max_value; // string max value
    unsigned int num_digits; // max num base digits that fit
} ;

// GLOBAL ARRAY!  Holds a TABLE of (above) Values ...
// to ease using index only in range of 1..36
Values TABLE[ 36+1 ]; // index 0 is NOT used here

const string REP = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

// call this at BEGINNING of program ... to fill table
void fill( Values table[] );


string toBaseX( UL input, int nbase ) …
David W 131 Practically a Posting Shark

See this (reworked) example ... (now with a struct)

that has a friend ...

an overloaded operator <<

// dequeExample.cpp //

#include <iostream>
#include <deque>

#include <queue>

struct Contact
{
    std::string name;
    int id;

    Contact( std::string n="", int i=0 ) : name(n), id(i) {}


    friend std::ostream& operator << ( std::ostream& os, const Contact& c )
    {
        return os << c.name << '[' << c.id << ']';
    }
} ;

int main()
{
    std::deque < Contact > dq;
    dq.push_back( Contact( "Fran", 2 ) );
    dq.push_back( Contact( "Joe", 1 ) );
    dq.push_back( Contact( "Moe", 3 ) );
    dq.push_back( Contact( "Jan", 5 ) );

    std::queue < int > q;

    std::deque < Contact >::const_iterator it;
    for( it = dq.begin(); it != dq.end(); ++it )
    {
        std::cout << *it << ' ';
        q.push( it->id ); // make copy
    }

    std::cout << std::endl;

    int size = q.size();
    while( size )
    {
        int tmp = q.front();
        std::cout << tmp << ' ';

        q.pop();
        q.push( tmp );

        --size;
    }

    std::cout << "q.size() = " << q.size() << std::endl;

}
David W 131 Practically a Posting Shark

Not really needed ...

Just use the C++ overloaded operator << to define how you wish to print a struct (or class)... when using iterators

Can use a friend function, if you wish.

See this edit ... (of your above attempt to print a queue).

// dequeExample.cpp //

#include <iostream>
#include <deque>

#include <queue>

int main()
{
    std::deque < int > dq;
    dq.push_back( 2 );
    dq.push_back( 1 );
    dq.push_back( 3 );
    dq.push_back( 5 );

    std::queue < int > q;

    std::deque < int >::const_iterator it;
    for( it = dq.begin(); it != dq.end(); ++it )
    {
        std::cout << *it << ' ';
        q.push( *it ); // make copy
    }

    std::cout << std::endl;

    int size = q.size();
    while( size )
    {
        int tmp = q.front();
        std::cout << tmp << ' ';

        q.pop();
        q.push( tmp );

        --size;
    }

    std::cout << "q.size() = " << q.size() << std::endl;

}
David W 131 Practically a Posting Shark

Your code makes NO sense ... THINK what you are doing!

Try what I (edited and) posted above ... for deque.

// dequeExample.cpp //

#include <iostream>
#include <deque>

int main()
{
    std::deque < int > dq;
    dq.push_back( 2 );
    dq.push_back( 1 );
    dq.push_back( 3 );
    dq.push_back( 5 );

    std::deque < int >::const_iterator it;
    for( it = dq.begin(); it != dq.end(); ++it )
        std::cout << *it << ' ';
}
David W 131 Practically a Posting Shark

Do you know what an iterator is? (Or a constant iterator? ... to traverse each address in a deque ... so ... you can access the values at each address ... an iterator is just an elegant pointer ... ++it from begin ... check that NOT == end ... and you have access to each 'it' as you traverse from dq.begin() ... to != dq.end()

deque< int >::const_iterator it;

for( it = dq.begin(); it != dq.end(); ++ it ) 
    cout << *it << " ";

If ... rather that a deque of int ... you had a deque of some struct ...

then ... first define overloaded operator << for that struct to print it out as per above.

David W 131 Practically a Posting Shark

You know .. the joy of having access to your own PC and compiler ... is that you can fairly quickly 'try things out for yourself ... and see.'

Enjoy :)

P.S. Your idea seems logical ... yes? ... But ... some 'queues' may offer random access?

Click Here

David W 131 Practically a Posting Shark

Did you read the link I gave you on your other post? (Please do not have multiple theads ... on the same subject.)

Click Here

David W 131 Practically a Posting Shark

You seem to have this 'backwards' :)

You load (assign) data into (each member in) a data struct

Then you add (push) each loaded (data) struct to the queue.

Code your stuct

struct Contact
{
    string name;
    int id;

    Contact( string n="", int i=0 ) : name(n), id(i) {}
} ;

queue < Contact > myQ; // construct empty queue
Contact tmp( "David", 717 );
myQ.push( tmp );
// etc ...
David W 131 Practically a Posting Shark

And ...

you could also ... simply do input like this:

// monthDayYear.cpp //

#include <iostream>
#include <string>

using namespace std;



int main()
{
    int mon;
    int day;
    int year;
    char dummy;

    const string month[] =
        {
            "January", "February", "March",
            "April", "May", "June",
            "July", "August", "September",
            "October", "November", "December"
        };


    cout << "Enter a date in the form MM/DD/YYYY: ";
    cin >> mon >> dummy >> day >> dummy >> year;

    cout << mon << "/" << day << "/" << year << endl;

    cout << month[mon-1] << " " << day << ", " << year << endl;


    return 0;
}

Also note: substr length below should probably be coded as a 2 (not a 3, even though atoi will ignore the trailing '/' char each time)

//////////////////////////////////0123456789//
cout << "Enter a date in the form MM/DD/YYYY: ";
string date;
getline( cin, date );

month = atoi(date.substr(0,2).c_str());
day = atoi(date.substr(3,2).c_str());
year = atoi(date.substr(6).c_str()

cout << mon << "/" << day << "/" << year << endl;
David W 131 Practically a Posting Shark

Look here for some more ideas about getting input ...

Click Here

Do you see the code option ... use that to submit code to preserve the indentation

#include <iostream>

// do NOT use to keep code portable
//#include<conio.h> 

int main() // NOT void main
{
    // clrscr(); // NOT portable code
    std::cout<<"Hello World!!!";
    // getch(); // NOT portable code

    std::cout << "Press 'Enter' to continue ... ";
    std::flush;
    std::cin.get();
    return 0; // if left off, C++ will supply this
}

Now ... code for some input of a, b and c

David W 131 Practically a Posting Shark

Use a struct and the C++ STL queue to hold those data structs

David W 131 Practically a Posting Shark

A queue ... is just a first in ... first out (FIFO) data structure ...

What are you trying to do with a queue ... C++ has one in the STL that you can test out, and use.

Click Here

David W 131 Practically a Posting Shark

Do you know how to code a 'Hello World' C++ program?

Do you know how to get integer user input (using cin) with a prompt for input?

Do you know how to code to test if a is zero ?

Do you know what 7 % 3 is ... in C++ ? ( or... 6 % 3 ? )

Do you that a && b is true only if both a is true and b is true?

Start with a working 'Hello World' shell ... and add / compile / test from there.

When you get into a bind ...afer going back to your lasting working stage ... and trying again from there ...

Show us your last working stage ... and the compiler errors printed out where you can not see what the problem is.

David W 131 Practically a Posting Shark

If the account balance falls below $800.00 at any time during the month, there is a $5.00 service charge for the month. This fee is only charged ONCE per month.

You will need to keep a 3rd variable (perhaps a bool 'flag') to handle this.

Passing all this info back and forth, suggests a struct is the 'way to go' to hold all the present info

struct Account
{
   double balance;

   // reset fees to zero at end of month 
   // but first subtract from balance
   // after checking ... if below == true

   double fees; // keep running total for month

   bool below; // if true at end of month
               // add 5 to monthly fee total
               // then ... reset to false
} ;

Note:
-> a struct can contain functions to process the data there
-> a struct can have a constructor to set inital values

If you do not wish to use a struct, you can add a 3rd variable, and pass in by reference, so that the value is updated in the 'calling scope'.

David W 131 Practically a Posting Shark
//NOTE Oops ...
unsigned value;

cout << "Please enter a positive number: ";

while (!(cin >> value) || value < 0) // Oops value is 'unsigned' so will never be < 0
// but ... may accept, i.e. no error flag raised, input of neg values ... but re-expressed as a different positive value

An alternate way:

#include <iostream>

using namespace std;

int main()
{
    int value;

    for( ; ; )
    {
        cout << "Please enter a positive number: ";
        if( cin >> value && value >= 0 && cin.get() == '\n' )
        {
            break;
        }
        else
        {
            cout << "Invalid input\n";
            cin.clear();
            while( cin.get() != '\n' ) ; // 'flush' cin stream
        }
    }

    cout << "You entered " << value << '\n';
David W 131 Practically a Posting Shark

Yes ... you are correct ...

A string has: string s = "message";
A char has: char c = '!';

#include <string>

// ...

int main()
{
    std::string input = "" // nice to show, but not needed since "" IS default constructor value

    while( input != "exit" )
    {
        std::cout << "OS#: ";
        getline( std::cin, input );

        if( input == "a" )
        {
            std::cout << "hello";
        }
    }
}
David W 131 Practically a Posting Shark

This next link may also give you some ideas for input in a loop ...

Note the steps.

6 Steps

David W 131 Practically a Posting Shark

Here is my 'OLD Borland' Turbo compiler output ...

(after I removed the initial assignment of a 0 value ... that 'Turbo' didn't appreciate ... but ... it only issued a warning.)

C:\Borland\myfiles>bcc32 convert3_uses_scanf.cpp
Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
convert3_uses_scanf.cpp:
Turbo Incremental Link 5.00 Copyright (c) 1997, 2000 Borland

C:\Borland\myfiles>pause
Press any key to continue .

You can see ... it compiled error and warning free.

(What were you errors?)

Here is where I edited (out) the assignent of the initial zero value ...

/* Uses scanf to get buffer input of upto maxStrLen ... */
/* NOTE: returns static buffer ... */
char* takeInStr( const char* msg, unsigned maxStrLen )
{
    const unsigned bufLen = BUF_SIZE;
    static char buf[bufLen];
    unsigned len; /*** was: unsigned len = 0; ***/

    if( maxStrLen < bufLen )
    {
        /* on example of a C 'forever loop' ...
           until break from loop or return from function */
        for( ; ; )
        {
            printf( msg );
            fflush( stdout );
            scanf( "%79s", buf ); /* adjust if change BUF_SIZE */
            fflushStdin();

            len = strlen( buf );
            if( len <= maxStrLen )
                return buf;
            /* else ... Ireach here ... */

            printf( "\nError! myMax input string length here "
                    "is %d char's long ...\n"
                    "but your string was %d char's long.\n",
                    maxStrLen, len );
        }
    }
    /* else ... if reach here ... */
    printf( "\nERROR!  The bufLen of %d needs to be "
            "greater than %d\n", …
David W 131 Practically a Posting Shark

Here is some of my really old code ... that I found, and quickly cleaned up a little, so it would compile ok ... under C90 ... It that may give some more ideas?

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

typedef struct twoDArray
{
    int **p;
    int rows;
    int cols;
} matrix ;

typedef matrix* pMatrix;

/*
   'createMatrix' returns a pointer to a C struct ...
   The 'struct' holds a 'pointer to a pointer to int' for the 2-D array 
   AND ALSO holds the number of rows and cols for the 2-D array.
*/
pMatrix createMatrix( int, int );
void showMatrix( pMatrix );
void freeMatrix( pMatrix );



int main()
{
    int i, j;
    int r = 2, c = 4;
    int count = r*c*2;
    pMatrix pM1, pM2, pM3;

    pM1 = createMatrix( r, c );
    /* fill in some values ... */
    /* int i, j; */
    for( i = 0; i < pM1->rows; ++i )
        for( j  =0; j < pM1->cols; ++j )
            pM1->p[ i ][ j ] = count--;

    pM2 = createMatrix(r, c);
    /* fill in some values ... */
    for( i = 0; i < pM2->rows; ++ i )
        for( j = 0; j < pM2->cols; ++j )
            pM2->p[ i ][ j ] = count--;

    pM3 = createMatrix(r, c);
    /* sum first two matrices ...*/
    for( i = 0; i < pM2->rows; ++i )
        for( j = 0; j < pM2->cols; ++j )
            pM3->p[ i ][ j ] = pM2->p[ i ][ j ] + pM1->p[ i …
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

Yes ... you can have a file to be included ... that is just a list of other file 'includes' ... that you need included. Make sure that you have 'unique guards' in the .h header files...

Note: you can NOT define the same thing after it has been previously define ... not allowed in C/C++ (like it is in Python ... where a name can be reused and bound to anything ... on the fly.)

#ifndef HEADER_FILE1_H
#define HEADER_FILE1_H

// ... ALL your declarations go here ...

#endif

These guards are to prevent the same header files ... (used/needed by various .cpp files, to be complied) ... to be included more than once.

David W 131 Practically a Posting Shark

You might like to look at split.h ... that emulates the Python split function in C

A C string input, with the delimiters, returns a Clist of 'words' (dynamic C strings)... parsed out in accord with your choice of delimiters passed in.

split.h

David W 131 Practically a Posting Shark

@Schol-R-LEA ... thanks for the AStyle indenting link.

Just for the fun of it, I revised my above version that used fgets ... so that it NOW ... ONLY USES SCANF, instead.

One possible student benefit, if this feature is wanted, is that using scanf, for string input, will NOT accept an empty line. Just pressing enter will not work there.

Note: the above could be a liability in some situations, as well as the inability of scanf, for string input, to get a whole line with embedded white-spaces.

But scanf is great to parse a line of words / tokens.

@john.kane.100483 ... this example may be more to your liking ?

/* convert3_uses_scanf.cpp */

/* Note: this version uses scanf, (instead of fgets) ... */
/* Note: string input using scanf ...
         waits ...
         ... for something to be entered */

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

#define BUF_SIZE 80

#define MENU "*** CONVERSION FROM YOUR CHOICE OF BASE " \
             "TO BASE 10 ***\n\n" \
             "b - Binary\n" \
             "o - Octal\n" \
             "h - Hexadecimal\n\n" \
             "Enter your choice "

void fflushStdin()
{
    char c;
    while( scanf( "%c", &c) && c != '\n' ) ;
}
int takeInChar( const char* msg )
{
    char chr;
    printf( msg );
    fflush( stdout );
    scanf( "%c", &chr );
    if( chr != '\n' ) fflushStdin();
    return chr;
}

int more() /* defaults to 'yes'/'1' ... unless 'n' or 'N' entered */
{
    if( tolower( takeInChar( …
David W 131 Practically a Posting Shark

You may also like to see using strchr ... the C string version of finding a char in a C type string?

Note the use of 'pointer arithmetic', when using strchr, to find the index (offset) value of the found char ... if found.

/* findCharInString3.cpp */

/* comparing ...
   1. C++ library char find... function
   2. C++ 'roll your own char find... function
   3. C style char find... function ... (strchr)
*/


#include <iostream>
#include <string>  /* C++ string or use your own class String */
#include <cctype> /* re. tolower */

/* Today's C++ uses <cstring> ... and not <string.h> */
#include <cstring>  /* re. strchr */


using namespace std;

/* Note: it is considered good style to use C++ library
   and not to 'roll your own' functions ... */
int lastIndexCharFoundIn( const string& s,  char c )
{
    int i;
    for( i = s.size() - 1; i >= 0; --i )
    {
        if( s[i] == c ) break;
    }
    return i; /* returned value is >= 0 if found, else -1 */
}

/* recall C/C++ char's are stored as integer values ... */
int takeInChar( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}

int main()
{
    do
    {
        cout << "Enter a line of …
David W 131 Practically a Posting Shark

If you write a small program to loop through all the char's a..z and A..Z

and take the difference of each matching pair ...

the results may give you a 'heads up' on what you may be seeking ?

for( int c = 'a', c2 = 'A'; c <= 'z'; ++c, ++c2 )
   // printout c, c2 and difference between c and c2
David W 131 Practically a Posting Shark

Here is a common 'show data' example ... that may help you to get started ... ( Oops ... looks like I missed the post just now of Dani's 'Ancient Dragon' :)

// twoArrays.cpp //

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

using namespace std;

const int NUM_COMPANIES = 6;

const int NUM_COLS = 4;

void print( const string[], const int[][NUM_COLS], int size );


int main()
{
    string companies[] = {"SDF","VXC","CCL","REL","MPL","GHB"};

    int sales [][NUM_COLS] =
    {
        {10000, 70000, 60000, 80000},
        {35000, 55000, 34000, 60000},
        {35000, 46000, 17000, 29000},
        {29000, 30000, 31000, 38000},
        {42000, 44000, 46000, 45000},
        {20000, 23000, 35000, 43000}
    };

    cout << setw(10) << "Company"
         << setw(10) << "sales1"
         << setw(10) << "sales2"
         << setw(10) << "sales3"
         << setw(10) << "sales4" << endl;

    print( companies, sales, NUM_COMPANIES );

    cin.get();
}


void print( const string co[], const int sales[][NUM_COLS], int size )
{
    for( int i = 0; i < size; ++i )
    {
        cout << setw(10) << co[i];
        for( int j = 0; j < NUM_COLS; ++j )
            cout << setw(10) << sales[i][j];

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

Will you be reading back from file to fill arrays?

David W 131 Practically a Posting Shark

It looks like you have 6 companies ...

And sales for 4 periods for each company ?

This lends itself to a (data) struct
using ONE array of struct (or better a C++ vector of struct)

(NOT 2 arrays ... that is 'old-school'!)

struct MyBus
{
   string name;
   double[4] sales;
} ;

where you could use a file data structure like this

sales1 sales2 sales3 sales4 company name till end
next lines ... as above ...

to write the data for each company all on one line

Then ... the read back is easy ... just read the lines and parse each line using stringstream ...to fill each struct

Note:
your file structure might begin with a line holding the number of companies to be read

then followed by a line holding the number of sales periods for each company

then all the data lines would follow.

David W 131 Practically a Posting Shark

Take a look at this simple example ...

/* findCharInString.cpp */


/*

    ... say for example if I have the string:

    "I like to program"

    and if I wanted to find out the *INDEX* of the char 't'
    how would I get a value for that index =  7 ?

*/

#include <iostream>
#include <string>  /* or use your own class String */
#include <cctype> /* re. tolower */

using namespace std;

/* BUT ... better to use C++ library than to 'roll your own' */
int lastIndexCharFoundIn( const string& s,  char c )
{
    int i;
    for( i = s.size() - 1; i >= 0; --i )
    {
        if( s[i] == c ) break;
    }
    return i; /* returned value is >= 0 if found, else -1 */
}

/* recall C/C++ char's are stored as integer values ... */
int takeInChar( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}

int main()
{
    do
    {
        cout << "Enter a line of text: " << flush;
        string testLine;
        getline( cin, testLine );

        cout << "Enter the char to find: " << flush;
        char c = cin.get();
        while( cin.get() != '\n' ) ; /* 'flush' cin stream ... */

        int i = lastIndexCharFoundIn( testLine,  c );
        if( i != -1 )
            cout << "Last found was at index " << i << endl;
        else
            cout << c << " was NOT found in " << testLine
                 << endl;
    }
    while( more() ) ;
}
David W 131 Practically a Posting Shark

Take a look at this simple example ...

/* findCharInString.cpp */


/*

    ... say for example if I have the string:

    "I like to program"

    and if I wanted to find out the *INDEX* of the char 't'
    how would I get a value for that index =  7 ?

*/

#include <iostream>
#include <string>  /* or use your own class String */
#include <cctype> /* re. tolower */

using namespace std;

/* BUT ... better to use C++ library than to 'roll your own' */
int indexCharFoundIn( const string& s,  char c )
{
    int i;
    for( i = s.size() - 1; i >= 0; --i )
    {
        if( s[i] == c ) break;
    }
    return i; /* returned value is >= 0 if found, else -1 */
}

/* recall C/C++ char's are stored as integer values ... */
int takeInChar( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}

int main()
{
    do
    {
        cout << "Enter a line of text: " << flush;
        string testLine;
        getline( cin, testLine );

        cout << "Enter the char to find: " << flush;
        char c = cin.get();
        while( cin.get() != '\n' ) ; /* 'flush' cin stream ... */

        int i = indexCharFoundIn( testLine,  c );
        if( i != -1 )
            cout << "Found at index " << i << endl;
        else
            cout << c << " was NOT found in " << testLine
                 << endl;
    }
    while( more() ) ;
}
David W 131 Practically a Posting Shark

Oops ... just noticed above, don't need to take tolower in the switch ... as added both lower and upper cases ... so that now each selection has two cases that select for it.

See updated 'main' below ...

int main()
{
    char* str;
    unsigned long result;

    do
    {
        int okToPrint = 1;

        printf( MENU );
        str =  takeInString( "(b, o or h):  " );

        switch( str[0] ) // changed from above code
        {
        case 'b': case 'B':
            result = binary2Decimal();
            break;
        case 'o': case 'O':
            result = octal2Decimal();
            break;
        case 'h': case 'H':
            result = hexa2Decimal();
            break;
        default:
            printf( "\nThe choice '%c' is not "
                    "implemented here ... try again.\n", 
                    str[0] ) ;
            okToPrint = 0;
        }

        if( okToPrint)
            printf( "\nDecimal equivalent is: %lu\n", result );

        str = takeInString( "\nMore numbers to convert (y/n) ?  " );
    }
    while( tolower(str[0]) != 'n' && printf( "\n" ) );

    return 0;
}
David W 131 Practically a Posting Shark

Hey ... always so nice to hear back from a 'happy coder'.

Enjoy your code!

You may be spending SO MUCH time coding ... or trying to figure out some code ... and that time spent could be a BIG problem ... especially, if you don't enjoy what you are doing :)

David W 131 Practically a Posting Shark

This may be what you were looking for ?

#include <iostream>

using namespace std;

int const ROWS = 2;
int const COLS = 3;

void print( int a[][ROWS][COLS], int numTables );
void print( int a[ROWS][COLS] );

int main()
{

    int ary3d[][ROWS][COLS] =
    {
        {
            {1,2,3},
            {4,5,6}
        },

        {
            {7,8,9},
            {0,1,2}
        },

        {
            {3,4,5},
            {6,7,8},
        },

        {
            {9,0,1},
            {2,3,4}
        }
    } ;

    int numTables = sizeof( ary3d ) / sizeof( ary3d[0] );

    print( ary3d, numTables );
    cout << "\nnumTables = " << numTables << endl;

    return 0;
}


void print( int a[ROWS][COLS] )
{
    for( int i = 0; i < ROWS; ++ i )
    {
        for( int j = 0; j < COLS; ++ j )
            cout << ' ' << a[i][j];
        cout << endl;
    }
}

void print( int a[][ROWS][COLS], int tables )
{
    for( int i = 0; i < tables; ++i )
    {
        cout << "Table " << i+1 << endl;
        print( a[i] ); // print table i
        cout << endl;

    }
}
David W 131 Practically a Posting Shark

I think what you are looking for is 'error handling' for input of 'invalid data' ... so that your running program will NOT then crash ... when the user enters invalid data.

You may like to see this (simple student) example of getting valid integer input from the user:

Click Here

See example 3.

David W 131 Practically a Posting Shark

This related example may help ...

may give you some ideas ?

// classStack.cpp //


#define MAX_ITEMS 50

template < typename T >
class Stack
{
public:
    Stack();
    bool isEmpty() const;
    bool isFull() const;
    void push( const T& );
    void pop();

    T top() const;
    T topPop();

    int size() const;

    void printStack() const;
private:
    int top_index;
    T info[MAX_ITEMS];
} ;



#include <iostream>

template < typename T >
Stack < T >::Stack()
{
    top_index = -1;
}

template < typename T >
bool Stack < T >::isEmpty() const
{
    return( top_index == -1 );
}

template < typename T >
bool Stack < T >::isFull() const
{
    return( top_index == MAX_ITEMS-1 );
}

template < typename T >
void Stack < T >::push( const T& item)
{
    if( isFull() )
        std::cout << "Stack is full" << std::endl;
    else
    {
        ++top_index;
        info[top_index] = item;
    }
}

template < typename T >
void Stack < T >::pop()
{
    if( isEmpty() )
        std::cout << "Stack is Empty" << std::endl;
    else
        --top_index;
}

template < typename T >
T Stack< T >::top() const
{
    if( !isEmpty() )
        return info[top_index];
    else
    {
        std::cout << "Stack is Empty" << std::endl;
        return T(0);
    }
}

template < typename T >
T Stack < T >::topPop()
{
    T it = top();
    pop();
    return it;
}


template < typename T >
int Stack< T >::size() const
{
    return top_index;
}

template < typename T >
void Stack< T >::printStack() const
{
    int i = top_index;
    while( i >= 0 ) …
David W 131 Practically a Posting Shark

Ok ... this uses fgets ... (it's just an edited alternate version -> for your added benefit <- of the clean coding, already supplied to you, by Dani Virtuoso ... Schol-R-LEA),

(since you REALLY SHOULD learn how to use fgets ... as well as scanf and fscanf ... if you wish to do input in C++ ... but, NEED there, to use a C style of input!)

Note: here two often annoying problems with fgets get fixed.

  1. the returned string is always trimmed of any '\n' char at the end
  2. if the buffer size used for fgets was too small, the rest of that line is 'flushed' / 'discarded'

This example also features

-> input validation

and

-> re-use of a function, with a passed in const C string prompt, to facilitate getting user C string input.
(Note: the static C string 'buffer' used inside and returned, after it is used, by that function.)

/*  Note: using C style coding here ...
    so that program can be compiled with a C++  
    OR 
    a C compiler */

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

#define BUFSIZE 80

#define MENU "*** CONVERSION FROM ANY BASE TO BASE 10 ***\n\n" \
             "b - Binary\n" \
             "o - Octal\n" \
             "h - Hexadecimal\n\n" \
             "Enter your choice "


/* function prototypes */

/* NOTE: uses/returns a 'static C string buffer' inside
         buffer is length BUFSIZE ... so max len of
         C string returned is BUFSIZE - 1

   NOTE: 'fixes fgets' …
David W 131 Practically a Posting Shark

Pass a pointer

David W 131 Practically a Posting Shark

Re ... char (C++ string) input ...
Did you ever think to look here ?

LOOK Here

David W 131 Practically a Posting Shark

This was the output I got of the code I sent you:

Conversion from any base to base 10
a - Binary
b - Octal
c - Hexadecimal
Select a value to be converted: c
[HEX TO DECIMAL CONVERSION]
Enter a Hex number: ae

174
Decimal equivalent is: 174

David W 131 Practically a Posting Shark

You do show some nice style in your coding ...

But ... it is NOT good to use NON standard code ... as a general practice ... you want to have skill in coding PORTABLE code ... code that conforms to the present C++ standard.

You might like to see this edit of your code, with some fixes ...

Keep up the neat coding you are doing ... it sure makes it a joy for others to read :)

// newStudentConversion.cpp //

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

#include <algorithm> // re. reverse ...

using std::cout;
using std::cin;
using std::endl;
using std::flush;
using std::string;


int takeInInt( const string& msg, int min = 0, int max = 100,
                                const string& errMsg = "\nError!\n" )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' && val >= min && val <= max )
            break;
        else
        {
            cout << errMsg;
            cin.clear();
            cin.sync();
        }
    }
    return val;
}

char takeInChr( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}

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

bool isvalid( const string& s, int base )
{
    // char bot = '0';
    char top;
    if( base <= 10 ) top =  '0' + base-1;
    else top = 'A' …
David W 131 Practically a Posting Shark

Did you test / see the effect of all the added ?

flushStdin();

After all the input ... to ensure that stdin is always flushed BEFORE you try to get any NEXT input ...

Try the FIXED /edited example program out ... and SEE!

David W 131 Practically a Posting Shark

See other post ...

Please ensure all your example code is placed with indenting preserved.

NO one wants to try to read C++ code that has NO proper indentation !!!

Avoid indiscriminate use of global variables.

Use descriptive variable names.

Declare your variables just before used with sufficent scope only as needed.

Avoid NON portable code ...
(an example of NON portable code is code that uses conio.h and windows.h)

DO NOT EXPECT people to have an ancient version of a C++ compiler (like Turbo C++) to check your code ... if you wish help from people who are using up-to-date C++ compilers ... you WILL have to adjust the code yourself to work on an old non-standard compiler ... AND ...provide code for us to see and test and mend ... that is designed to compile ... and so will compile ... on a present day standard C++ compiler!

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

In the last few days, I have noticed a very old thread ... resurrected ... about a non-standard C getline function.

To all who may like a C readLine function ... a C function that reads in a dynamic C string of any length ... a function with a similar feel to the C++ getline function ... please feel free to use readLine.h (to access readLine) ... or readWord.h (to access readWord)

These are freely available at:

For ... readLine and readWord ... Click Here

David W 131 Practically a Posting Shark

Since you are coding in C++, why don't you use C++ string to hold your 'numbers' ... of ANY LENGTH?

David W 131 Practically a Posting Shark

I just noticed ... that you have posted the very same problem at ... at least two other help sites ...

That is NOT the way to learn how to program ... looking for some-one to give you the code !!!

BUT ... I have ALREADY given you an unique algorithm to solve your 'problem' ... that uses a 'struct' ... and that first validates user input, etc.

However, the code that you show me back, each time ... shows NO evidence, what-so-ever, that you have studied or tried to implement that algorithm ... or any validation features ... and the code you show me back also uses fixed length C strings, with the max length pre-fixed at compile time ... not any variety, (that I can see), of C++ string.

If you do not wish to learn how to code ... for yourself ... in C++ ...why should I bother further ... to give away insights, that were very costly for me ... both in time and work ... for me to acquire ???

David W 131 Practically a Posting Shark

Maybe something like this ...
(that uses C++ string, stringstream objects, etc...)

// distanceTwoCitiesList_sort3.cpp // // 2014-03-04 //

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

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

using namespace std;

/*
    Make sure you allow them to choose their options
    by both the number and the capitalized letter(s) of the choice.

    If your list is full and they choose to enter another city,
    have them choose to either NOT enter the new city or to overwrite
    one of the earlier cities (they choose which one).
    Print the list of cities for them to choose from.
    (Remember, you still can't exceed your maximum list size!)

*/
#define MAX_SIZE 10  // can use this and change size here as needed ...

/*
    add a submenu to sort the city list. The submenu should allow
    the user to choose whether to sort by name, x coordinate,
    or y coordinate. (Note: You can't simply sort by location since
    there is no way to compare 2D points without reference to
    a common line.) Just like the main menu, your submenu choices
    should be choosable by either their number or their capitalized
    letter. Have a fourth option to return to the main menu.
    (Implying that you'll stay in the submenu until they choose that
    option.)

    let user load and save city information from/to files.
    You can decide the format of …
David W 131 Practically a Posting Shark

Here is an example ... (that instead of using C++ string, includes its own class String ... the same class String that I supplied you the link to ... above.)

Note: the sort would be faster (more efficent) if the vector, after input of a line (String) held (at input) Items (stuct) ... formed then, instead of formed from strings ... while sorting, in the compare function.

// 2_test_sortAlpahNum.cpp // // 2014-03-04 //

// tests out class String etc... //

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


// for 'quick/cheap' test ... use these includes below ... //

#include "base_string.cpp"
#include "string.cpp"

//#include "case.cpp" // NOT used here
//#include "reverse.cpp"  // NOT used here

////////////////////

#include <iostream>
#include <fstream>
//#include <sstream> // not used here now with this class String ...
//#include <string> // using above class String

#include <vector>  // NEED STL vector ... (OR some STD like, vector class included)

#include <algorithm> // Need STL re. sort
#include <ctype.h>    // re. isdigit, isalpha, tolower // Modern C++ uses <cctype> //
#include <stdlib.h>  // re. atoi // Modern C++ uses <cstdlib> //

using namespace std; // Modern C++ has and uses namespace //



typedef vector< String > VecStr; // Note: using STL vector BUT above class String

// takes in whole line ... returns int value of 1st char ... or zero
int takeInChar( const String& msg ) // In C/C++ char's have int values ...
{
    cout << msg << flush;
    String reply;
    getline( cin, reply );
    if( reply.size() ) …
David W 131 Practically a Posting Shark

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

David W 131 Practically a Posting Shark

My code works exactly as you mentioned above, I need help with the following:

Make sure you allow them to choose their options by both the number and the capitalized letter(s) of the choice.

case '1' : case 'A' : // rest of code ...

If your list is full and they choose to enter another city, have them choose to either NOT enter the new city or to overwrite one of the earlier cities (they choose which one). Print the list of cities for them to choose from. (Remember, you still can't exceed your maximum list size!)

Again ... you seem to NOT be using the C++ STL list container here ... if you use the STL list, you can just push_back all new objects to add to the list ... as long as there is still memory available.

add a submenu to sort the city list. The submenu should allow the user to choose whether to sort by name, x coordinate, or y coordinate.

(Note: You can't simply sort by location since there is no way to compare 2D points without reference to a common line.)

Not exactly true ... you COULD define a compare function.

Just like the main menu, your submenu choices should be choosable by either their number or their capitalized letter.

See above ...

Have a fourth option to return to the main menu. (Implying that you'll stay in the submenu until they …