David W 131 Practically a Posting Shark

Just an example to try to get Dani in the top listing of Google search ... of just part 'a'

(Part 'b' should be easy to add to the menu as choices 3 and 4 with function calls for each.)

// FahrenheitToCelsiusAndViceVersa.cpp //

// demo of ...
// 'how a student might do validation of numeric input'

// see "Six Fast Steps to Programming in C++"
// http://developers-heaven.net/forum/index.php/topic,2022.0.html

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

using namespace std;

/*
    http://en.wikipedia.org/wiki/Fahrenheit

    Fahrenheit to Celsius : (°F - 32) ÷ 1.8 =°C

    Celsius to Fahrenheit : (°C × 1.8) + 32 =°F
*/

const string MENU =
      "1) Fahrenheit To Celsius\n"
      "2) Celsius To Fahrenheit\n"
      "Your choice (1 or 2) ? ";

// some utilities ...

double takeInDbl( const string& msg,
                  const string& errMsg =
                  "\nOnly numbers are a valid entry here!\n" )
{
    double val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
            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;
}


// ... functions to convert ...

void FahrenheitToCelsius()
{
    double f = takeInDbl( "\nEnter Fahrenheit temperature to …
David W 131 Practically a Posting Shark

I didn't see a link to Dani (in the top links) in that Google search ...

Maybe it's time to do a nice student example ... using a menu and functions ... also with a function to vaidate the numeric input?

David W 131 Practically a Posting Shark

Can you show us the code you have so far, so that we can see how you are doing?

If you sincerely wish for help with your then submitteed code ...

-> REMEMBER <-

to select all your submitted code and then press the tab key to indent it all ... one tab ... (this will PESERVE your code indentation when it is shown in the DANI browser.)

David W 131 Practically a Posting Shark

Can you show us the code you have so far, so that we can see how you are doing?

If you sincerely wish for help with your then submitteed code ...

-> REMEMBER <-

to select all your submitted code and then press the tab key to indent it all ... one tab ... (this will PESERVE your code indentation when it is shown in the DANI browser.)

David W 131 Practically a Posting Shark

Or ...you could return a struct like this, after all processing done, to easily report the 'stats' for BOTH of height and weight ...

(You could store weight stat's using index 0, and height stat's using index 1)

typedef struct
{
   float min[2];
   float max[2];
   float mean[2];
   float mode[2];
   float stdDev[2];

} MyStats ;
David W 131 Practically a Posting Shark

Your program logic flow could be made clearer by using individual functions for each 'job' ...

A common way to get your data is to read it from a file.

Suppose the file held the height (inches) and weight (pounds) of a large number of people for you to process.

Suppose also that the file data was structured as follows:

// file name: HeightWeight.txt
60.5 205.5
56.25 153.5
// ... etc

Now, you could read all this data into an array ...
(with the max array size pre-fixed, at compile time, to be large-enough) ..

i.e. an array of C struct

using something like this:

typedef struct
{
   float height;
   float weight; 

} HeightWeight;

int fillFromFile( const char fname[], HeightWeight ary[], int max_ary_size )
{
   FILE* fin = fopen( fname, "r" );
   int size = 0;
   if( fin )
   {
      while( size < max_ary_size && fscanf( fin, "%f %f", &ary[size].height, &ary[size].weight ) == 2 ) ++ size;

     fclose( fin );
     return size;
   }
   else return -1; /* to 'flag' file open error */
}

Now in main, you would do something like this:

HeightWeight ary[100]; /* get space for 100 records */
int size = fillFromFile( "HeightWeight.txt", ary, 100 );
if( size != -1 )
{
   /* process the array of data  */
}
else printf( "No data read ... check file name ok\n" );

As you process your data, you could call (a) function(s) that find and return the values you …

David W 131 Practically a Posting Shark

Your program logic flow could be simplified by using several functions ... one function to do each 'job'.

Then you can simply call those functions in sequence.

A common way to get your data is to read it from a file.

Suppose the file held the height (inches) and weight (pounds) of a large number of people for you to process,

Suppose also that the file data was structured as follows:

// file name: HeightWeight.txt
60.5 205.5
56.25 153.5
// ... etc

Now, you could read all this data into an array ...
(with the max array size pre-fixed, at compile time, to be large-enough) ..

i.e. an array of C struct

using something like this:

typedef struct
{
   float height;
   float weight; 

} HeightWeight;

int fillFromFile( const char fname[], HeightWeight ary[], unsigned max_ary_size )
{
   FILE* fin = fopen( fname, "r" );
   int size = 0;
   if( fin )
   {
      while( size < max_ary_size && fscanf( fin, "%f %f", &ary[size].height, &ary[size].weight ) == 2 ) ++ size;

     fclose( fin );
     return size;
   }
   else return -1; /* to 'flag' file open error */
}

Now in main, you would do something like this:

int size = fillFromFile( "HeightWeight.txt", ary, 100 );
if( size )
{
   /* process the array of data  */
}
else printf( "No data read ... check file name ok\n" );
David W 131 Practically a Posting Shark

You may like to look at these C examples that emulate some of the functions and objects available in C++

Beyond Beginning Computer Programming in C ...

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

C SOME UTILITY functions ...

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

split.h ... a C emulation of the Python spilt function to parse a string ...

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

Six Fast Steps to Programming in C

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

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

Just change the top line in the example ... to:

int fillAryFromFile( const char fname[], char Customer ary[], int max_size )
David W 131 Practically a Posting Shark

any programmer here???

Many ... do you have a C++ coding question? Please show the code you have so far and any error messages. Please state the problem (you think) you are having as simply and as clearly as possible. We are not mind readers... but many here are very seasoned at helping you get started on the right track ... once we see 'where you are heading' vs 'where you really wanted to go.'

David W 131 Practically a Posting Shark

Looking at what you had at the link you provided ...
if the data in your file is all pre-validated ...

i.e. ...

1) if the C strings are all less than 30 char's long (just one word, no spaces in 'word')

2) id#'s all fit into an unsigned short

3) if the data in the file is perfectly regular with idNuum on 1st line, name on next line, a valid float on 3rd line, (or all data has just whitespace between each data field)

then you easily could hande like this:

struct Customer 
{
    unsigned short int IDnum;
    char name[30];
    float salesCustomer; 
} ;

// ...

int fillAryFromFile( const char* fname, char Customer ary[], int max_size )
{
    int size = 0;
    ifstream fin( fname );
    if( fin )
    {
        while
        (
            size < max_size &&
            fin >> ary[size].IDnum &&
            fin >> ary[size].name &&
            fin >> ary[size].salesCustomer
        }
        {
            ++size;
            if( size == max_ size )
            {
                cout << "You have reached max size.\n";
            }
        }
        fin.close();
        return size;
    }
    // else ... if reach here ...
    cout << "There was a problem opening file.\n";
    return -1; // flag value for file open error
}
David W 131 Practically a Posting Shark

You are making it much harder than it is ...

printf( ...) is a function
int main( ... ) is a function

Functions are really easy ...

(once you 'see' that ...
functions are just named blocks of code that can accept values passed in ... and then execute that block of code when ever called by the name you give that function...)

Fuctions help you 'see' the logic flow readily

int size = takeInFileData( fname, ary, maxArySize );
if( size != -1 ) // -1 was value returned if error with file open
{
    findAverageAndReport( ary, size );
}
else
   //print error message re file open problem
David W 131 Practically a Posting Shark

Enter first letter (scan to see if letter, if not tell user to try again)

Enter second letter (scan again as above, see if letter 2 = letter 1. if yes, try again)

Enter third (scan above again)

Enter fourth (same again)

Enter fifth (last time

And ... what do think this does (if ARY_SIZE was 5) ?
(copy/pasted from above, with a few changes in comments)

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 ) ) /* 'scan' to see if letter */
   {
      if( !alreadyExist( c, ary, size ) )
      {
         ary[size] = c; /* Ok, accept (i.e.append) */
         ++size; /* get ready for next entry */
      }
      else
         printf( "The letter %c already exists, try again.\n", c );
   }
   else
      printf( "%c is NOT valid ... try again.\n", c );  
}
David W 131 Practically a Posting Shark

Hi please help me, im trying to make a program that only accepts numbers ...

The presumption is that you are taking in a string
then validating that string to ensure it only contains
characters in the range '0'..'9'

You could use a function like this:

bool isNonNegInt( const string& test )
{
   // can test from back to front if desire ... //
   for( int i = test.size()-1; i >= 0; --i )
   {
      if( test[i] < '0' || test[i] > '9' )
         return false;
   }
   // if reach here, all passed, so can now ...
   return true;
}

You may also like to use these 3 handy utilites ...

string takeInString( const string& msg = "" )
{
    string val;
    cout << msg << flush;
    getline( cin, val );
    return val;
}
char takeInChr( const 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;
}

After all the includes needed, like:

#include <iostream>
#include <string>
#include <cctype> // re. to lower

and ...

using namespace std;

Then in main, you could code something like this ...

do
{
   string testVal = takeInString( "Enter a non negative integer: " );
   if( isNonNegInt( testVal ) )
      cout << "Good! You entered " …
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

Not sure what you are trying to do in your class 'test' ...

Is it supposed to be a class for arrays of integers with a pre-fixed maximun size?

If that is what you are trying to code, this example may give you some ideas ?

// test_classMyArray.cpp //


#include <iostream>
#include <cassert>


using namespace std;

const int MAX_ARY_SIZE = 10;

class MyArray
{
public:
    MyArray() : len(0)
    {
        for( int i = 0; i < MAX_ARY_SIZE; ++i )
            ary[i] = 0;
    }
    MyArray( int size, int initVal )
    {
        assert( size <= MAX_ARY_SIZE );
        len = size;
        for( int i = 0; i < len; ++i )
            ary[i] =initVal;
    }

    void set_size( int size )
    {
        assert( size <= MAX_ARY_SIZE );
        len = size;
    }
    int size() const { return len; }

    typedef int* iterator;
    iterator begin() { return ary; }
    iterator end() { return ary+len; }

    typedef const int* const_iterator;
    const_iterator begin() const { return ary; }
    const_iterator end() const { return ary+len; }

    int& operator [] ( int );
    const int& operator [] ( int ) const;

private:
    int ary[MAX_ARY_SIZE];
    int len;

    friend ostream& operator << ( ostream&, const MyArray& );
} ;


ostream& operator << ( ostream& out, const MyArray& c )
{
    for( int i = 0; i < c.len; ++ i )
         out << c.ary[i] << ' ';
    return out;
}

int& MyArray::operator [] ( int index )
{
    assert( index >= 0 && index < MAX_ARY_SIZE );
    return ary[index];
}
const int& …
David W 131 Practically a Posting Shark

You are right ... it is NOT correct code to return a ref to that temporary value.

You need to have your compiler warnings turned ON. (You seemed to have all turned off.)

David W 131 Practically a Posting Shark

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

David W 131 Practically a Posting Shark

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

Why don't you Google 'example uses of static variables in C++ or C' ... or something like that ... you will learn, by the 'where' and 'why for' of usage ... much.

... glad to clarify, but if you are serious about learning to program, learning to use Google, or other search engines is key.

Hint, how long does a static variable persist in memory?

  1. Until you exit a program?
  2. Until you exit a function where it is declared?
  3. Until the cows come home?
  4. Until you pull the plug?

Also, Google ...
what gets stored on stack
what gets stored on heap
and perhaps study up on 'read only memory', while you are at it.
(mutable memory vs immutable)

David W 131 Practically a Posting Shark

How many different codes can 8 bits hold?
...........................16 .........?
...........................32 .........?
...

What you want each unique bit pattern to mean, is up to you.

Do you know what 2's compilement means? (If not, Google it.)

So, 8 bits has 256 unique code that could represent the numbers 0..255
or
-128..127

or any other 256 items you might chosse to encode and then to decode.

David W 131 Practically a Posting Shark

So ... as @NathanOliver and @L7Sqr and other of Dani's friends have suggested ... you could use this, to provide only what you need to permit the program to recognise the items from the std namespace ... and so then to compile ok.

string and stringstream need to be qualified with std:: or you need to put using namespace std; in your code after you includes.

using namespace std; 
#include "Date.h"

Putting this all together, try using ...

using std::string;
using std::stringstream;

// then ... and only then ...

#include "Date.h"  // Note: Date.h would have been better
                     // coded with std:: before each item from
                     // std namespace
                     // to avoid you having to add
                     // the 2 lines above
David W 131 Practically a Posting Shark

Again @mike_2000_17, thank you for your thoughtful answers.

I have pretty much, to-date, avoided using exceptions in C++, and instead, checked the various values returned ... or the error flag states set, when doing io, memory allocation, etc...

Having enjoyed using HLA ... and then Python exception handling, I have not really 'seen' much of how ... or when ... to 'nicely' handle exceptions ... in C++

Your example code above, however, really looked interesting and useful.

I too, first thought of using:

if( !fin.is_open() )
    throw file_not_openable(FNAME);

as a way to handle that 'problem' ...

but elected to see if there was some existing/avaible other way that I could use ... thus the code I tried above that seemed to also do the particular job desired.

But I think the way, you used in your code, makes for clearer code 'logic flow' and clean read-ability.

Thanks again for taking the time to comment ... and all the useful insights.

David

David W 131 Practically a Posting Shark

A nice (general) way to handle questions like this might be to use a (data) struct (record) ...

/* def'n of struct ... */
typedef struct
{
   char code; /* 'A', 'B' or 'C' */
   char* info; /* a dynamic C string to hold text */
   int dollars;
} Item ;

This keeps all you data together, and you could then use an array of type Item to hold as many Item objects as you have memory available ...

as opposed to using ...

parallel arrays or multi-dimension arrays.

But... if your particular problem is limited to just 3 objects, you might like to use parallel arrays ... and a table look up method, something like this:

const char code[] = { 'A', 'B', 'C' );
const int size = sizeof code / sizeof code[0];

const char* info[] = { "apple_pie", "buns_48", "cherry_crate" );
const int dollars[] = { 10, 20, 30 };


int findIndex( const char code[], int size, char x )
{
   int i;
   for( i = 0; i < size; ++i )
      if( x == code[i] ) return i;
   /* else if reach here ...  */
   return -1; /* the value to indicate NOT found */
}

Then ...

// in main

// perhaps inside a big do loop ... while more?

int index;

// prompt for x, input of a code in range 'A'..'C'

// get index of that code ..

index = findIndex( code, SIZE, x );

// print out …
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

Firstly ... take a look at this in your 'main' function:

Stack outer_stack;

Stack inner_stack; // probably want this here ???

for( int i = 0; i < 100000; ++i )
{
    //Stack inner_stack; // really ???
    inner_stack.push(some_data); //WHAT is 'some_data' ... is it 'i' ? or some value depending in 'i' ?

    //inner_stack = outer_stack; //problem line !
    // ... do you really want to make a copy after each
    // new data item was added to inner_stack ? //
}

//maybe you want to make a COPY WHEN DONE ???
inner_stack = outer_stack;

I have NOT looked at the rest of your code ... but this, in main, looked very unusual!

David W 131 Practically a Posting Shark

No ...

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

Note ... you also could grow new objects ...'step-wise'

as ...

could code a class Matrix using a vector of vectors

then could code a class Cube using a vector < Matrix >

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 code a shell 'hello world' program that compiles and gives the expected output?

Well, if you can do that ... then think how you might print out all those *** char's

Hint: Maybe use a loop that prints a line of ***
with the number of *** that you want on esch line.

Show us what you can do? We need to see your best code effort ... so far :)

Hint2:
If you want to print a grid ...
you could form a 2D matrix, in memory, of the pattern that you want ... then print out each row.

Also ... study / try out the example code ... the code on the other (old) page where you appended your first post here at Dani's place.

David W 131 Practically a Posting Shark

Your question and example output are really very well given to you ...

Oops ... that is NOT the case ... the example output given when the balance exceeds the credit limit does not match the written spec's.

I would GO WITH the written spec's.

Thus the example (of last lines of) output when the new balance exceeded the credit limit should have looked like this:

Account: 15
Limit  : 2500
Balance: 2900
Credit limit exceeded

For those customers whose credit limit is exceeded, the program should display the customer’s account number, credit limit, new balance, and the message "Credit limit exceeded"

Also ... your function:

/* return value is 1 to continue or 0 to quit */
int takeInAccInfo( AccountInfo* acc );

rather than have a 'void' return value should rather return an 'int' ...
(as per the comment line above the function prototype)

David W 131 Practically a Posting Shark

A simple method to get you started is always to carefully read the question over and compare that to 'the example output' ...

(Your question and example output are really very well given to you ... and you could start out with a small working shell first step program ... that might be to code just to enter one data set - one struct ...
and then to print that record back to the screen.)

You could use a C struct to hold your data.

It could look like this:

typedef struct
{
   int accountNo;
   int startBalance;
   int totalCharges;
   int totalCredits;
   int creditLimit;
} AccountInfo ;

/* a few functions ... like one to fill up a struct */

/* example of function prototypes you could use */
void takeInAccInfo( Account* acc );
void calAndPrintAccInfo( Account* acc );
int more();
/* you could use others also ... */

/* NOTE": you must define these before using */

/* then in main */

/* start taking in one record and reporting ... */
int main()
{
    do
    {
        AccountInfo tmp; /*get memory to hold info*/
        takeInAccInfo( &tmp ); /* pass in address */
        calAndPrintAccInfo( &tmp ); 
    }
    while( more() );

    return 0;
}

/* // so this can guide all your input prompts
Enter account (-1to end): 3
Enter Beginning Balance: 3500
Enter Total Charges: 750
Enter Total Credits: 300
Enter credit Limits: 4000

*/

/* //and this will quide your output (after calculations)
Account: 100
Balance: 3950
*/

David W 131 Practically a Posting Shark

Can you show your code?

David W 131 Practically a Posting Shark

Can you show your code where you think the problem arises?

And also explain, what you think that code is supposed to do.

It may simply be that you have a path and or fileName not set properly ?

David W 131 Practically a Posting Shark

Probably was searching the web and found this page ?

So @nonc...

Welcome to Dani's place and her C++ help forum.

You may not know how to start a new thread?

Click on the BOX at the top, or bottom, that says:

Start New Discussion

And then enter a short title that is consistent with your C++ programming question ...

Then enter your question and the example of your code where you think you are 'stuck'.

Make sure you select all the code block ...

and then ...
tab/indent it all ...

to preserve the proper indentation in your example code.

And don't forget to fix up the spelling and grammar before submitting your 'page'.

David W 131 Practically a Posting Shark

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

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

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

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

#ifndef Stack_h
#define Stack_h

#include "SLList.h"

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

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

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

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

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

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

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

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

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

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

#include "STACK.H"


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

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

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

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

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

using namespace std;


// some utilities used here ...

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

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



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

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

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

lastPtr = newPtr;

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

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

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

Firstly ...

get your SLList working and tested ok.

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

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

David W 131 Practically a Posting Shark

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

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

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

Take a look:

Firstly the file: "LISTNODE.H"

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

#ifndef LISTNODE_H
#define LISTNODE_H

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

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

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

#endif

Then the file: "SLList.h"

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


#ifndef SLLIST_H
#define SLLIST_H

#include "LISTNODE.H"

#include <iostream>
#include <stdexcept>

template < typename NODETYPE >
class SLList
{
public:

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

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

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

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

Not fixed yet ...

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

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

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

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

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


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

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

And here ...

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

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

        lastPtr = ?? ;// hint as above

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

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

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

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

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

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

David W 131 Practically a Posting Shark

@ mike_2000_17 ... and your advanced approach would also allow speeds ups in reading data from very large files by ...

and call it with:

std::vector< int > v;
v.reserve( MY_LARGE_FILE_SIZE_BEST_GUESS_PLUS_SOME );
fillFromFile( FNAME, std::back_inserter(v) );
David W 131 Practically a Posting Shark

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

# processlargeFile.py #

FNAME = 'largeFile.txt'

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

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

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

David W 131 Practically a Posting Shark

Also, it is 'int main()' and do not use 'getch()' if you want your code to be portable.

Please remember that you are asking experienced C programmers for their valuable time and some free advice ... so probably it is your best interests, to present your problematic code as simply and as clearly as possible :)

David W 131 Practically a Posting Shark

Just a quick scan and I noticed this:

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

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

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


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

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

Best thing here ...
really ...
is to use the STL vector container :)

For example ...

vector< int > fillVecFromFile( const string& FNAME )
{
   vector< int > v;
   v.reserve( 100 ); // or whatever best quess of file size
   ifstream fin( FNAME.c_str() )
   if( fin )
   {
      int tmp;
      while( fin > tmpInt ) v.push_back( tmpInt ); 
      fin.close();
   }
   else
      cout << "There was a problem opening file "
           << FNAME << endl;
   return v;
}

Or, maybe even better ...

bool fillVecFromFile( const string& FNAME, vector< int>& v )
{
   v.clear();
   v.reserve( 100 ); // or whatever best quess of file size
   ifstream fin( FNAME.c_str() )
   if( fin )
   {
      int tmp;
      while( fin > tmpInt ) v.push_back( tmpInt ); 
      fin.close();
      return true;
   }
   //else
  cout << "There was a problem opening file "
       << FNAME << endl;
  return false;
}
David W 131 Practically a Posting Shark

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

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

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

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

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

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

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

David W 131 Practically a Posting Shark

This may be a little simpler C code ... to get you started?

-> NO dynamic memory used (stack size pre-fixed at compile time)

-> also uses a 'table look-up' method

-> note the simple struct used

/* stack_stuff2.c */

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


#define SIZE 100

#define TRUE 1
#define FALSE 0

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;
}


typedef struct
{
    int top;
    char items[SIZE];
 } Stack ;

int empty( Stack* ps )
{
    if( ps->top == -1 )
        return TRUE;
    /* else */
    return FALSE;
}

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

void push( Stack* ps, char c )
{
    if( ps->top < SIZE-1 )
        ps->items[ ++ps->top ] = c;
    else
    {
        printf( "Stack Overflow" );
        exit(2);
    }
}

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


char takeInChr( const char* msg )
{
    char …