David W 131 Practically a Posting Shark

If you'd like a 'nudge' about how to get started ... then please just ask.

Can you code to print a prompt and then take in a string?

If the first 5 char's of the string, (the first 2 strings),
are always the customer ID,
can you then code to extract that first 5 char sub-string?
(google C++ substr)

Can you then get the remaining char's and convert to an int?

After doing above twice ... (maybe using a loop?) ...
can you then code to print a prompt and take in an int ?
(maybe use: cin >> intValue;)

OK ... let's see your best attempt to code the above steps ...

Hint:
code/compile/test in steps ...

Firstly code a working shell C++ program that compiles ok and
prints out your prompt ok.

Then add in steps, testing each step as you go,
and see how far you can get.

Then ask for help if needed from there,
but show us the code that compiled and worked ok,
and the code for the last step where you had a problem.

Edit:
If you are to read each data set from a long file,
then could firstly open file ... as fin ... and then ...

if( fin )
{
   while( fin >> str1 >> str2 >> intValue )
   {
       // proccess data and show desired output
   }
   fin.close(); // close file
}
else // print error …
David W 131 Practically a Posting Shark

You really do need to show us what you have tried so that we may see where you are having difficulty.

There are exceeding many 'C++ class' example programs all over the WEB ... that could give you good ideas about how to get started.

For a recent example of a 'beginning student level' ... 'C++ class' program ... here at Dani's awesome student help place ... you may like to see this:

https://www.daniweb.com/software-development/cpp/threads/498056/class-and-objects

But do send in the code you have tried so far ... you may be amazed at all the helps freely given here ... after you make your best effort to start!

David W 131 Practically a Posting Shark

You might like to see this ...

Directed Graphs (digraph) and Weighted Directed Graphs (wdigraph)

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

It may help you to get started?

David W 131 Practically a Posting Shark

Please edit above to be:

#include <cmath> // re. acos, sqrt //
David W 131 Practically a Posting Shark

Check you code with this ...

// dotProduct.cpp //  // 2015-07-23 //

// find dot product and angle between ... two (2D) vectors (Points) //

#include <iostream>
#include <string>
#include <cmath> // re. ceil

// ok to do this, for now
using namespace std;

const string INTRO =
    "This program asks for input in a loop ... \n";

const double DEG_PER_RAD = 180.0 / acos(-1);


double takeInDbl( const std::string& msg,
                  const std::string& errMsg = "Error! Try again ...\n" ) ;


class Point
{
public:
    // ctor...
    Point( double x=0, double y=0 ) : x(x), y(y) {}

    void takeIn()
    {
        while( true )
        {
            x = takeInDbl( "Enter x: " );
            y = takeInDbl( "Enter y: " );
            if( x == 0 && y == 0 )
            {
                cout << "Point(0, 0) is NOT a valid entry here ...\n";
            }
            else break;
        }
    }

    double length() const
    {
        return sqrt( x*x + y*y );
    }

    double operator * ( const Point& pb ) const
    {
        return ( x*pb.x + y*pb.y );
    }

    Point operator / ( const double& dbl ) const
    {
        return Point( x/dbl, y/dbl );
    }

    Point unit() const
    {
        return *this / length();
    }

private:
    double x, y;

    friend ostream& operator << ( ostream& os, const Point& pt )
    {
        return os << "(" << pt.x << ", " << pt.y << ")" ;
    }
} ;


bool more( const string& msg = "More (y/n) ? " );



int main() ////////////////// BEGIN MAIN ///////////////////
{
    cout << …
David W 131 Practically a Posting Shark

Actually ... the following is a lttle more accurate (and also less code) ... It (also) makes (some) allowance, re. the count of bricks, for the 'walls MORTAR' at the 'finishing edges' ...

// bricks2.cpp //  // 2015/07/23 //

// find approximate count of bricks needed for a wall //

#include <iostream>
#include <string>
#include <cmath> // re. ceil

// ok to do this, for now
using namespace std;

const string INTRO =
    "This program asks for input in a loop ... \n";

const double MORTAR = 3.0/8 ; // in inches //

const double LOSSAGE = 0.05 ; // adjust here to what fits best //


template< typename T >
T takeIn( const std::string& msg,
          const std::string& errMsg = "Error! Try again ...\n" ) ;


class Box
{
public:
    // default ctor ...
    Box() : length(8), height(3), width(4) {} // default brick size in inches //

    void takeInSides()
    {
        length = takeIn< double > ( "Enter length in inches: " );
        height = takeIn< double > ( "Enter height in inches: " );
    }
    double sideArea() const { return (length+MORTAR)*(height+MORTAR); }

private:
    double length, height, width;

    friend ostream& operator << ( ostream& os, const Box& bx )
    {
        return os << bx.length << " x " << bx.width << " x " << bx.height;
    }
} ;


bool more( const string& msg = "More (y/n) ? " );



int main() ////////////////// BEGIN MAIN ///////////////////
{
    cout << INTRO << endl;
    do
    {
        Box brick;
        cout << "For bricks …
David W 131 Practically a Posting Shark

In C++ ... a 'struct' is an object.

The difference is that a C++ 'class' defaults to 'private' ...

but a C++ 'struct' defaults to 'public' ...

const double MORTAR = 3.0/8 ; // in inches //
const double LOSSAGE = 0.05 ; // adjust here to what fits best //

template< typename T >
T takeIn( const std::string& msg,
          const std::string& errMsg = "Error! Try again ...\n" );

class Box
{
public:
    // default ctor ...
    Box() : length(8), height(3), width(4) {} // default brick size in inches //

    void takeInSides()
    {
        length = takeIn< double > ( "Enter length in inches: " );
        height = takeIn< double > ( "Enter height in inches: " );
    }
    double sideArea() const { return length*height; }
    double sideAreaAugmented() const { return (length+MORTAR)*(height+MORTAR); }

private:
    double length, height, width;

    friend ostream& operator << ( ostream& os, const Box& bx )
    {
        return os << bx.length << " x " << bx.width << " x " << bx.height;
    }
} ;
David W 131 Practically a Posting Shark

You might start out with a loop ... something like this:

// bricks.cpp //  // 2015/07/22 //

// this version approximates count of bricks needed for a wall ... //

#include <iostream>
#include <string>
#include <cmath> // re. ceil

// ok to do this, for now
using namespace std;

const string INTRO =
    "This program asks for input in a loop ... \n";

const double MORTAR = 3.0/8 ; // in inches //

const double LOSSAGE = 0.05 ; // adjust here to what fits best //


template< typename T >
T takeIn( const std::string& msg,
          const std::string& errMsg = "Error! Try again ...\n" )
{
    T val = T();
    while( true )
    {
        std::cout << msg << std::flush;
        if( std::cin >> val && std::cin.get() == '\n' )
            break;
        else
        {
            std::cout << errMsg;
            std::cin.clear(); // clear error flasgs
            std::cin.sync(); // 'flush' cin stream ...
        }
    }
    return val;
}

struct Box
{
    double length, height, width;

    // default ctor ...
    Box() : length(8), height(3), width(4) {} // default brick size in inches //

    void takeInSides()
    {
        length = takeIn< double > ( "Enter length in inches: " );
        height = takeIn< double > ( "Enter height in inches: " );
    }
    double sideArea() const { return length*height; }
    double sideAreaAugmented() const { return (length+MORTAR)*(height+MORTAR); }

    friend ostream& operator << ( ostream& os, const Box& bx )
    {
        return os << bx.length << " x " << bx.width << " x " << bx.height;
    }
} ;

bool more( …
kumanutiw commented: Thax but I am required to do with only class and objects...also no mortar and filling is required..no need to corner filling as well...Simply rect wal +0
David W 131 Practically a Posting Shark

It is not really the vol of the totalLength x totalHeight x totalWidth of a wall the determines the (min) integer number of bricks needed to brick up a real wall that has mortar between the bricks and openings for doors and windows and door and window frames and cut bricks to make them all fit neatly !!! (And do not forget what happens at the corners ... and that each next layer of bricks is symmetrically staggered with respect to the layer below.)

David W 131 Practically a Posting Shark

You need to firstly solve the math before you can code ...

It is often helpful to solve a much simpler problem at first.

If you start out with a retangular solid wall of height hw and width ww the surface area Aw = hw*ww

And if the side surface area of a brick is Ab = hb*wb

Then ... you would need a minimum of Aw / Ab bricks ...
(without allowing for mortar, openings, or losses due to cut bricks to fit height and width and openings exactly.)

Once you have an algorithim to find the minimum integer number of bricks for some real wall, you can then apply that to each of the 4 outer walls ... and then to each of the 4 inner walls ... once you know the exact spec's for the height and width of each outer (or inner wall) ... and the dimensions of the bricks ... and the space to be left between the walls.

David W 131 Practically a Posting Shark

Can there be a vector of structures?

Yes

I am guessing that with data.push_back(temp) the .push_back(temp) is a feature of the vector type. But, it does not seem to indicate a specific element identification in the vector data. How would you access something like the 123rd element in the vector?

struct Student
{
    string name;
    string id;
    /*
    //ctor... but not used / needed in this demo //
    Student( const string& name="", const string& id="" ) 
        : name(name), id(id) {}
    */
    void takeIn()
    {
        cout << "Enter name: " << flush;
        getline( cin, name );
        cout << "Enter id: " << flush;
        getline( cin, id );
    }
    print() const
    {
        cout << name << ", " << id << '\n'; 
    }
} ;

// ...other stuff ...

bool more(); // need to define these before calling below //

void print( const vector< Student >& studs )
{
    for( size_t i = 0; i < studs.size(); ++ i )
    {
        //cout << studs[i].name << ", " << studs[i].id << '\n';
        studs[i].print();
    }
}


int main()
{
    // get an empty vector to hold 'Student objects'
    vector< Student > yourStuds;

    do
    {
        Student tmp;
        tmp.takeIn();
        yourStuds.push_back( tmp ); 
    }
    while( more() );

    cout << "Showing all the students:\n";
    print( yourStuds );
}

What happens if you try to access the 123rd element and there are only 120 data items recorded? With an array it would return giberish (some random value that was stored in that …

David W 131 Practically a Posting Shark

Can you show us the code you have tried so far?

We really have no idea what your problem is ... until you show us that code.

Try this next link ....

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

to get some ideas how to get started with input of data in a loop.

David W 131 Practically a Posting Shark

Since this thread has been a little resuscitated ...

it may be the case that some beginning students in C ...

might like to know ...

that a simple bubble sort (usually used ONLY on very small data sets - arrays)

can be used effectively on a very large data set - array ...

*** IF ***

the collection is already sorted and a new element is added (at the end) ...

*** and IF THEN ***

the bubble sort ... then bubbles from the rear to the front.

/* bubble_sort2.h */

#ifndef BUBBLE_SORT2_H
#define BUBBLE_SORT2_H

#ifndef shaker_sort
#define shaker_sort 0
#endif

#ifndef back_to_front
#define back_to_front 1
#endif

#ifndef show_steps
#define show_steps 0
#endif


#if back_to_front

/* Iter's here are 'BI-DIRECTINAL' ... 
   (i.e. can traverse in both directions)
   This bubble-sort, bubbles from 'back-to-front' ... 
   so can call after a 'push_back' to stay sorted ... */
void bubble_sort( Iter beg, Iter end,  int (*cmp) (const void* a, const void* b) )
{
    /* so can stop if reach 'one before begin' */
#if show_steps
    Iter sav_beg = beg, sav_end = end;
#endif
    Iter right_el = --end;
    Iter left_el = right_el;

    int aswap = 1;
    --beg;
    while( aswap )
    {
#if show_steps
        putchar('\n');
#endif
        aswap = 0;
        while( --left_el != beg )
        {
            /* Note right, left order below ... when doing bubble_sort */
            if( cmp( right_el, left_el) < 0 ) /* Ok ... swap values */
            {
                MyType tmp = *left_el;
                *left_el = *right_el;
                *right_el = tmp;

                /* was a …
David W 131 Practically a Posting Shark

If you just wish to reverse the order of the lines in the array ...

try this:

/* demo_str_rev.c */


#include <stdio.h>


void str_rev( char* ary[],  int size )
{
    int i, j;
    for( i = 0, j = size-1; i < j; ++ i, --j )
    {
        char* tmp = ary[i];
        ary[i] = ary[j];
        ary[j] = tmp;
    }
}



int main()
{
    int i;
    char* lines[] =
    {
        "To err is human....",
        "But to really mess things up...",
        "One needs to know C!!"
    };

    const int size = sizeof lines / sizeof *lines;

    puts( "BEFORE reversing lines ... " );
    for( i = 0; i < size; ++ i )
         puts( lines[i] );

    str_rev( lines, size );
    puts( "AFTER reversing lines ... " );
    for( i = 0; i < size; ++ i )
         puts( lines[i] );

    return 0;
}
David W 131 Practically a Posting Shark

Or ...

if you'd like to use dynamic memory to hold each C string

and ...

a dynamic array to hold all the dynamic C strings ...

here is an easy way via using the code found in these (linked) files ...

readLine.h
http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864

and

Cvec.h
http://developers-heaven.net/forum/index.php/topic,2580.0.html
http://developers-heaven.net/forum/index.php/topic,2580.msg2862.html#msg2862

/* test_replace.c */

/* this example uses dynamic memory ... using readLine.h and Cvec.h */

/*
    ... need to find a substring in a array of char*
    and replace it with another string ...
*/

#include "readLine.h" /* include this at the top */

typedef struct myRec
{
    char* str;
} Rec ;

void freeVrec( Rec* pt )
{
    free( pt->str ) ;
}

/* NOW can include this ... */
#include "Cvec.h"

char* getRevisedStr( const char* line, size_t len, const char* old, const char* new )
{
    size_t lenOld = strlen(old),
           lenNew = strlen(new);

    char* buf = newMem( strlen(line) - lenOld + lenNew + 1 );

    strncpy( buf, line, len );
    strcpy( buf+len, new );
    strcpy( buf+len+lenNew, line+len+lenOld );
    return buf;
}


int main()
{
    const char* lines[] =
    {
        "We will teach you how to",
        "Move a mountain",
        "Level a building",
        "Erase the past",
        "Make a million",
        "All through C!"
    };
    const int sizeLines = sizeof lines / sizeof *lines;

    const char* s1 = " a";
    const char* s2 = " the";


    char* found = NULL;
    int i;
    Rec tmpLineRec;
    Cvec cv;

    initCvec( &cv ); /* MUST initial for Cvec …
David W 131 Practically a Posting Shark

Do you know how to code a working shell program in C++ ?

Do you know anything about using a C++ struct (or class) ...
to hold the data for each Student?

Do you know how to use the C++ library list (i.e. a double linked list) ?

Do you know how to code a compare function for the C++ list sort ?

If you can answer yes to all the above, then you are ready to code.

*Question-2:
Write a program to sort in ascending order students according to ID numbers and in descending order students marks(grades) using Doubly Linked List.
- Get three information as: ID number, Student name and one student Mark from user
- Show separately two sorted data:
- Sorted data (ID, Name, Mark) in ascending order according to students ID
- Sorted data (ID, Name, Mark) in descending order according to students Mark
- Entering data can be stopped in any style of programming as: entering negative number, '0', or 'Y' and 'N'...
- Use any sorting algorithm (Bubble, Selection or Insertion sort) to sort data*

In any case, there are numerous examples of similar problems ...
all over the web ...

like the example here:

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

If you need to code your own list, you could first solve your problem using the C++ library list ...

Then code / test your own list ... and sub that in when it is all debugged and tested to be …

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

If I understand your problem, the solution is to define an 'inverse function'

for each 'function' :

def numSquared( num ):
    return num*num

def inverseNumSquared( num ):
    return num**0.5
David W 131 Practically a Posting Shark

You could try something like this:

/* test_replace.c */

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

/*
    ... need to find a substring in a array of char*
    and replace it with another string ...
*/

#define MAX_SIZE 40

const char* getRevisedStr( const char* line, int len, const char* old, const char* new )
{
    static char buf[MAX_SIZE];
    size_t lenold = strlen(old),
           lennew = strlen(new);

    if( strlen(line) - lenold + lennew > sizeof buf -1 )
    {
        printf( "\nError, buffer was too small ... so unchanged line was returned...\n\n" );
        return line;
    }

    strncpy( buf, line, len );
    strcpy( buf+len, new );
    strcpy( buf+len+strlen(new), line+len+strlen(old) );
    return buf;
}


int main()
{
    char arr[][MAX_SIZE] =
    {
        "We will teach you how to",
        "Move a mountain",
        "Level a building",
        "Erase the past",
        "Make a million",
        "All through C!"
    };
    const int size = sizeof arr / sizeof *arr;

    const char* s1 = "mountain";
    const char* s2 = "car";

    char* found = NULL;
    int i;

    printf( "s1 = '%s' will be replaced by s2 = '%s' in arr\n", s1, s2 ) ;

    for( i = 0 ; i < size ; ++ i )
    {
        found = strstr( arr[i], s1 );
        if( found )
            strcpy( arr[i], getRevisedStr( arr[i], found-arr[i], s1, s2 ) );

        printf( "Line %d: %s\n", i+1, arr[i] ) ;
    }
    return 0;
}
David W 131 Practically a Posting Shark

Since this was your very first post at Dani's 'student friendly' place ...

Do you have any idea how to start?

  1. Is your data to be read from file ...
    or ...
  2. is it to be entered by the user via the keyboard after a prompt ...
    or ...
  3. is your program to handle both of the above cases?

If you have the 2nd case above ...

you could use an input loop something like this ...

int main()
{
    do
    {
        string line = takeInLine( "Enter a number followed by that many strings: " );
        vector< string > vec = split( line, " " );
        for( size_t i = 1; i < vec.size(); ++ i )
             process( vec[i] );
    }
    while( more() );
}

Now, of course, before you could call any (user defined) functions ...
you would have to define them ...

For example:

void process( const string& str )
{
    // your code goes here //
}

One way to handle processing the above string
would be to traverse it from beginning to end
and trying to build up a new string
that becomes the desired word ...
i.e to see if that 'string_built_up' == "nadia"

std::string word = "";
std::string seek = "nadia";
int seeklen = seek.size();
int maxlen = str.size();

int i = 0, j = 0;

for( ; i < maxlen; ++ i )
{
    if( str[i] == seek[j] )
    { …
David W 131 Practically a Posting Shark

You may like to see this link re. a way to handle new data types in C ...

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

David W 131 Practically a Posting Shark

You could try something like this:

// split_demo.cpp //

/*
    i need to parse the input into two categories:
    user age and user name.
    for example, the user input -->>
    [23:Frank] [15:Jack] [45:] [33:sofia] []
    in this case i have more than one argument (delimiter, total of 3 )
    which are [:],
    in addition ...
    i need to get user input and stop looping 
    once i encounter the [] at the end.
    in addition - what if one of the brackets is missing a name, 
    how can assign a blank name and ...
    skip that part in order to process the rest.
*/

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

const char* FNAME = "test.txt";
/*
[23:Frank] [15:Jack] [45:] [33:Sofia] []
[23:Fran] [15:Jade] [45:Joe] [33:Sommy] []
[23:Frew] [15:John] [45:Jim] [33:Suzanne] []
*/


std::list< std::string > split( const std::string& s, const std::string delimits = " \t" )
{
    std::list< std::string > tmp;
    size_t p1, p2 = 0;
    for( ; ; ) // loop forever ... until break
    {
        p1 = s.find_first_not_of( delimits, p2 ); // Note: p2 is 0 on first loop
        if( std::string::npos == p1 )
            break; // i.e. if empty or all delimits

        p2 = s.find_first_of( delimits, p1+1 );
        if( std::string::npos != p2 ) // i.e. if still more ... p2 is not past end
            tmp.push_back( s.substr( p1, p2-p1 ) );
        else
        {
            tmp.push_back( s.substr( p1 ) );
            break;
        }
    }
    return tmp;
}

bool isInt( const std::string& s )
{
    for( int len = s.size()-1 ; …
David W 131 Practically a Posting Shark

Your problem can be more easily handled if it's broken up into two BIG steps...

1st step:

Using the C++ library linked list, you can code and test out the code for the data processing...

2nd step:

You could then code/test a linked list ... and sub in that linked list for the C++ library list.

Below you can see related examples of doing just that ... If you study this, it could help you to get started.

Class Student using C++ library list ... AND ...

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

6 Fast Steps to a C++ template class List

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

David W 131 Practically a Posting Shark

If you can handle more ...

and if your spec's are to compile with a C++ compiler,

(but to restrict the 'io' to C style),

then ...

this example ...

may give you some more ideas to get you started with a working shell.

// entreEtudiant.cpp //

/*
    The presumption used here ...
    is that you wish to compile with a C++ compiler
    BUT ...
    restrict the io here to the C style ...
*/


#include <cstdio>
#include <cstring>


const int NOM_BUF_LEN = 8;
const int NOTS_NUM = 3;
const int NOM_NUM_MAX = 2; // keep small while testing //

const char* MENU = "1-Entre un etudiant  2-Print  3-Chercher un etudiant  4-Quit\n"
                   "Faites votre chois:  ";

// 2 utilities to ease input here ... //
char* fixedFgets( char* s, size_t bufSize, FILE* fin )
{
    if( fgets( s, bufSize, fin ) )
    {
        char *p = strchr( s, '\n' ),
             c ;
        if( p ) *p = 0; /* strip off '\n' at end ... IF it exists */
        else while( (c = fgetc( fin )) != '\n'  &&  c != EOF ) ; /* flush... */
        return s;
    }
    /*  else ... if reach here ... */
    return NULL;
}
int entreChr( const char* msg )
{
    printf( msg ); fflush( stdout );
    char chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}


// a C++ struct or class with all public //
struct Etudiant …
David W 131 Practically a Posting Shark

Your data-record structure is NOT what you need here ...

Try something like this:

// bloodGroups.cpp //

#include <iostream>
#include <string>

#include <cstring> // re. strcpy
#include <cstdio> // re. FILE


const char* FNAME = "users.bin";

const int MAX_NAME_LEN = 39;
const int MAX_ADD_LEN = 99;
const int MAX_BG_LEN = 15;

const char* MENU =
    "====== STUDENT DATABASE MANAGEMENT SYSTEM ======\n\n"
    "1. Add    Records\n"
    "2. List   Record\n"
    "3. Search Record\n"
    "4. Modify Records\n"
    "5. Delete Records\n"
    "6. Exit   Program\n\n"
    "Select Your Choice :=> ";


struct Student
{
    int id;
    char name[MAX_NAME_LEN+1];
    int age;
    char gender; // 'm' or 'f'
    char address[MAX_ADD_LEN+1];
    char blood_group[MAX_BG_LEN+1]; // AB Rho Negative (or Positive)
    char doc_name[MAX_NAME_LEN+1];
    int amount;
    char op_tr; // 'o' for op or 't' for tr
} ;


// 2 utilities follow ... (to facilitate VALID data entry) //

template< typename T >
T takeIn( const std::string& msg,
          const std::string& errMsg = "\nError! Try again ...\n\n" )
{
    T val;
    while( true )
    {
        std::cout << msg << std::flush;
        if( std::cin >> val && std::cin.get() == '\n' )
            break;
        else
        {
            std::cout << errMsg;
            std::cin.clear(); // clear all error flags
            std::cin.sync(); // 'flush' cin stream
        }
    }
    return val;
}
// return a (Non-empty) C string ... with up to maxLen char's ...
const char* takeInLineMaxLen( const std::string& msg, int maxLen,
                              bool okEmpty = false )
{
    std::string val;
    while( true )
    {
        std::cout << msg << std::flush;
        getline( std::cin, val );
        int len = val.size();
        if( len )
        {
            if( len …
David W 131 Practically a Posting Shark

If you mean that you want the program to prompt for a variable name, you would also want to prompt for the variable type.

You could use a C++ map to hold the (unique) name and a pointer to the (new) memory (allocated) to hold that type (and type name).

David W 131 Practically a Posting Shark

Can you write a 'prototype' for the function?

(That could get you started?)

David W 131 Practically a Posting Shark

P.S.

You may find some related examples here:

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

David W 131 Practically a Posting Shark

This example also ensures the prgram will NOT crash if bad data was entered:

// drawShape.cpp //

#include <iostream>

/*
**when compiling it gave me the right shape
and there is another sol whith a diff way but im not getting it
and the other sol goes like ...
**
    ####*  1
    ###*#  2
    ##*##  3 // Did you ??? forget this line ??? //
    #*###  4
    *####  5
*/

const int MAX_LEN = 8;


void drawShape( int n, char ch1, char ch2 )
{
    using std::cout; using std::endl;

    for( int i = 0; i < n; ++ i )
    {
        for( int j = n-1; j >= 0; -- j )
            if( j == i ) cout << ch2;
            else cout << ch1;
        cout << endl;
    }
}



int main()
{
    using namespace std;

    int n;
    char ch1, ch2;

    // get valid data ...
    bool done = false;
    while( !done )
    {
        cout << "Enter n, ch1, ch2: ";
        if( cin >> n >> ch1 >> ch2 && n <= MAX_LEN && n > 1 )
        {
            cin.sync(); // 'flush' cin stream
            done = true;
        }
        else
        {
            cin.clear(); // clear all cin error flags
            cin.sync(); // 'flush' cin stream
            cout << "\nIllegal entry! Number entered must be in range 2.."
                 << MAX_LEN << "\n\n";
        }
    }

    cout << "\nOk ... now drawing shape ... \n";
    for( int i = 0; i < n; ++ i )
    {
        for( int j = 0; j < n; ++ j …
David W 131 Practically a Posting Shark

You will find that help comes more readily if you present the problem clearly.

Provide the shortest amount of code possible to illustrate the problem.

State clearly the problem ...

i.e. do NOT just say:

'there is a problem' / 'something is not working' !

David W 131 Practically a Posting Shark

The data file example you provided above ... looks defective?

... Consider a data file named STORES.DAT, which contains inventory information for four shops. Each line in the file contains the inventory of five types of merchandize in each store ...

So ... the file has 4 lines.
BUT ... EACH line should have only 5 numbers (integers)!

Also, if you want portable code, do not use Windows system calls ...

Also, good to break up jobs into functions.
This also helps one to 'see' more easily the logic flow in the program.

You may like to see the example below:

// compareStores.cpp //

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


const char* FNAME = "stores.dat";
/*
 1 14  0  5  2
15 20  0  0  5
25  0 10 30 20
 4  5  3  3  6
*/

const int ROWS = 4, COLS = 5;


bool fillFromFile( int mat[][COLS], int aryMins[], int aryMaxs[], int totals[],
                   const char* inFileName )
{
    std::ifstream fin( inFileName );
    if( fin )
    {
        // read file into matrix ...
        for( int row = 0; row < ROWS; ++ row )
        {
            for( int col = 0; col < COLS; ++ col )
            {
                fin >> mat[row][col];
                if( col == 0 )
                    aryMins[row] = aryMaxs[row] = col;
                else
                {
                    if( mat[row][col] < mat[row][aryMins[row]] )
                        aryMins[row] = col;
                    else if( mat[row][col] > mat[row][aryMaxs[row]] )
                        aryMaxs[row] = col;
                }

                totals[row] += mat[row][col];
            }
        }
        fin.close();
        return true;
    } …
David W 131 Practically a Posting Shark

@Frederick2

Do you have any Windows graphic library function calls ...
anything like this ...

move_to(int x, int y);
move_to(double x, double y);

draw_to(int x, int y);
draw_to(double x, double y);

etc... ?

David W 131 Practically a Posting Shark

This little demo may help ...

// demo_cin.sync.cpp //

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


int takeInChr( const std::string& msg )
{
    std::cout << msg << std::flush;
    std::string reply;
    getline( std::cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
int takeInChr2(  const std::string& msg )
{
    std::cout << msg << std::flush;
    int c = std::cin.get();
    // std::cin.sync(); // or could use instead ... //
    if( c != '\n' ) while( std::cin.get() != '\n' ) ;
    return c;
}

bool more( const std::string& text = "" )
{
    if( tolower( takeInChr2( "More " + text +
                 "(y/n) ? " ) ) == 'n' )
        return false;
    // else ...
    return true;
}



int main()
{
    do
    {
        char c1 = toupper( takeInChr( "Enter the first letter of your 1st name: " ));
        char c2 = toupper( takeInChr2( "Enter the first letter of your 2nd name: " ));

        std::cout << "Hi " << c1 << '.' << c2 << ". How are you today?\n";
    }
    while(  more() ) ;
}
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

This may give you some more ideas ...

and some more tools (C utility functions) to use in your code:
(You could use a 'Clist' by including file Clist.h
available at ...

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

if your prefer)

/* 52Cards.c */

#include "readLine.h" /* re. myAssert */
#include <time.h>


const char kinds[] = { 'S', 'C', 'H', 'D' };
const char values[] = { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };



typedef struct
{
    char kind;
    char val;

} Rec;

void freeVrec( Rec* p )
{
    /* NO dynamic memory was used here, so NONE to free  ... */
}


/* NEED BOTH definitions above: typedef Rec  and  freeVrec ...
   and then can include ... */

#include "Cvec.h"

#define Card Rec /* equate */


void getNewDeck( Cvec* cards )
{
    int i, j;
    for( i = 0; i < 4; ++ i )
    {
        for( j = 0; j < 13; ++ j )
        {
            Card c;
            c.kind = kinds[i];
            c.val = values[j];
            push_backCvec( cards, &c  );
        }
    }
}
void shuffleDeck( Cvec* cards )
{
    int i, j, count = cards->size;
    Card tmp;
    while( count-- )
    {
        i = rand() % cards->size;
        j = rand() % cards->size;

        /* swap */
        tmp = cards->ary[i];
        cards->ary[i] = cards->ary[j];
        cards->ary[j] = tmp;
    }
}

void showDeck( const Cvec* cards )
{
    int i;
    for( i = 0; i < cards->size;  )
    {
        printf( "%c %c  ", cards->ary[i].kind,  cards->ary[i].val ) ;
        if( ++i …
David W 131 Practically a Posting Shark

It is possible to create some 'tools' (functions) in C that emulate things available in C++ and Python ...

Isn't Python coded in C?

You might like to try out some things in this mini library of C utilities ...

... function that are in the following files:

readLine.h
readWord.h
split.h // returns a Clist of parsed dynamic C string 'words' //
Cvec.h
Clist.h
etc...

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

David W 131 Practically a Posting Shark

We are not allowed to use strlen function. . :/

So ... can you code your own (safe) version of a 'strlen' function?

size_t mySafeStrLen( const char* strIn )
{
   size_t len = 0;
   if( strIn )
   {  
      const char* p = strIn;
     // rest of your code goes here
     //len = p-strIn; // using pointer arithmetic //
   }
   return len;
David W 131 Practically a Posting Shark

It would help if you would completely re - design your code ...

You are best to use the standard C++ containers ...

like vector, list, stack, etc ...

rather than messing around with your 'nodes', etc...

Also, build your code in steps, fixing each step as you go,
and keeping copies of all the previous WORKING stages ...

(A 'working stage' is code that gives the exact expected output for all the possible input at that stage.)

Then ... you can always go back to a previous 'working stage' ...

and start over from there,

if you cannot find the latest new 'bug'.

So ... show us the code for a 'working stage' ...

and then,

only the very next part that was added where you need help to see the 'bug'.

Also ... see changes

include <string>
#include <cstdlib>
#include <iostream>
// #include<malloc.h> // in C++ use new, but better to use C++ vector, etc
#include <fstream>
#include <ctime> //#include<time.h>
// #include<conio.h> // Do NOT use to keep your code portable //

// using namespace std; // bad idea to do this in big project //

const int SIZE = 10; //#define SIZE 10 // better C++ style ...

Also ...
break up your classes into their own files
(but you do not need so many classes ...
if you use C++ list and vector, etc... containers.)

This (old) example may help your re-design ...

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

David W 131 Practically a Posting Shark

@Syed Ammar

please read the previous posts in this thread,
especially the patient explanations by ...

@Schol-R-LEA & @deceptikon

David W 131 Practically a Posting Shark

This example of usage may help:

Note: files found here ...

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

/* testIt1.c */

#include "readLine.h" 
#include "CvecOfInt.h"

const char* FNAME = "test1.txt";
/*
    #include <stdio.h>
    #include <string.h>

    #define pi 3.14
    #define Pi 3.14159

    int main()
    {
      printf("The value of PI is %f", pi);
      return 0;
    }
*/


int main()
{
    FILE* fp = fopen( FNAME, "r" );
    if( fp )
    {
        char* line;
        Rec rc;
        Cvec cv;
        int i = 0;
        initCvec( &cv );
        while( (line = readLine( fp )) )
        {
            ++i;
            if( strchr(line, '#' ) )
            {
                rc.val = i;
                push_backCvec( &cv, &rc );
            }
            free( line );
        }
        fclose( fp );

        for( i = 0; i < cv.size; ++ i )
            printf( "There was a '#' char on line: %d\n", cv.ary[i].val );

        clearCvec( &cv );
    }
    else printf( "There was a problem opening file %s\n", FNAME );

    return 0;
}
David W 131 Practically a Posting Shark

This new little library of C functions,
that eases the reading and parsing of a line of text in C
(or 'words' of text)
may make your problem mush easier to handle ...

http://developers-heaven.net/forum/index.php/topic,2582.msg3142.html#msg3142

It permits using C dynamic strings,
almost as easily,
as one can use C++ strings
with getline and cin

( readLine emulates getline )

( readWord emulates cin >> )

( but remember to free all dynamic memory when done with it. )

See the example of usage provided.

David W 131 Practically a Posting Shark

Edit: (fixed comment)

void insertAt( const MyType& mt, size_t i )
{
    if( i <= len )
    {
        if( i == 0 ) push_front(mt);
        else if( i == len ) push_back(mt);
        else // at least 2 Nodes, head & tail exist, this goes in-between //
        {
            Node* prev = head;
            for( size_t j = 1; j < i; ++ j )
                 prev = prev->next;
            prev->next = new Node(mt, prev->next->next);
        }
    }
    else
        std::cerr << "\nERROR! Index out of bounds, so NOT inserted ...\n";
}
David W 131 Practically a Posting Shark

I suspect that you are over complicating things ?

Take a look at this simplification:

// outPutToBeFixed.cpp //

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>



const char* MENU =
    "Welcome to the DVD Collection Program! \n"
    "What do you want to do?\n\n"
    "1. Add DVD\n"
    "2. Remove DVD\n"
    "3. Update DVD\n"
    "4. Show DVDs\n"
    "0. EXIT\n"
    "Enter a number in range 0..4: ";


// some utilities useful here ... //

template< typename T >
T takeIn( const std::string& msg, const std::string& errmsg = "\nInvalid entry ... try again.\n\n" )
{
    T val;
    while( true )
    {
        std::cout << msg << std::flush;
        if( std::cin >> val && std::cin.get() == '\n' )
            break;
        else
        {
            std::cout << errmsg;
            std::cin.clear(); // clear cin error flags
            std::cin.sync(); // 'flush' cin stream ... //
        }
    }
    return val;
}
// return a (Non-empty) C++ string //
std::string takeInLine( const std::string& msg, bool okEmpty = false )
{
    std::string val;
    while( true )
    {
        std::cout << msg << std::flush;
        getline( std::cin, val );
        if( okEmpty )
            break;
        // else ...
        if( val.size() )
            break;
        // else ...
        std::cout << "\nEmpty line input is NOT valid here ...\n\n";
    }
    return val;
}




class DVD
{
private:
    std::string title;
    double length;
    int year;
public:
    std::string get_title() const { return title; }
    void takeInDVD()
    {
        title = takeInLine( "\nEnter the movie title: " );
        length = takeIn< double >( "Enter the length: " );
        year =  takeIn< int >( "Enter the year released: " );
    }
    void …
David W 131 Practically a Posting Shark

This may give you a start?

const string s = "abcd";
const string n = "1234";

for( size_t i = 0; i < s.size(); ++ i )
{
    cout << s[i] << n[i];
}
David W 131 Practically a Posting Shark

It is often a good idea to start with a simple (simpler) version ...

Get that working and then upgrade from there.

This simpler version may get you started and give you some file read / write ideas to facilitate your progress in your coding problem ...

// dataWriteRead.cpp //

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



const int NUM_EMPS = 2; // keep small while testing //

const double TaxRate = 0.15;
const double DepCost = 20.00;
const double OverTimeRate = 1.5;
const double BasicHours = 37.5;

const char* EMP_FILE = "emp_file.txt";
const char* PAY_FILE = "pay_file.txt";

const char* MENU =
    "1 add employees\n"
    "2 enter hours worked\n"
    "3 get pays\n"
    "4 show all employees\n"
    "0 quit\n"
    "Enter your choice 0..4: ";


// some utilities useful here ... //
template< typename T >
T takeIn( const std::string& msg, const std::string& errmsg = "\nInvalid entry ... try again.\n" )
{
    T val;
    while( true )
    {
        std::cout << msg << std::flush;
        if( std::cin >> val && std::cin.get() == '\n' )
            break;
        else
        {
            std::cout << errmsg;
            std::cin.clear(); // clear cin error flags
            std::cin.sync(); // 'flush' cin stream ... //
        }
    }
    return val;
}

// return a (Non-empty) C++ string //
std::string takeInLine( const std::string& msg, bool okEmpty = false )
{
    std::string val;
    while( true )
    {
        std::cout << msg << std::flush;
        getline( std::cin, val );
        if( okEmpty )
            break;
        // else ...
        if( val.size() )
            break;
        // else ...
        std::cout << "\nEmpty line …
David W 131 Practically a Posting Shark

I think you are forgetting you are coding in C++ ?

You may wish to try something like this ...

// addNodesIthPosition.cpp //  // 2015-05-11 //


#include <iostream>

typedef int MyType;


struct Node
{
    MyType data;
    Node* next;

    // default ctor...
    Node() : data(MyType()), next(0) {}
    // ctor's
    Node( const MyType& mt ) : data(mt), next(0) {}
    Node( const MyType& mt, Node* nxt ) : data(mt), next(nxt) {}
} ;

struct List
{
    Node* head;
    Node* tail;
    size_t len;

    // default ctor...
    List() : head(0), tail(0), len(0) {}
    ~List() { clear(); }

    void clear()
    {
        for( ; head != 0 ;  )
        {
            Node* cur = head;
            head = head->next;
            delete cur;
        }
        tail = 0;
        len = 0;
    }

    // copy ctor ...
    List( const List& lst )
    {
        head = tail = 0;
        len = 0;
        for( Node* cur = lst.head; cur != 0; cur = cur->next )
            push_back( cur->data );
    }
    // overloaded assignment ...
    List& operator = ( const List& lst )
    {
        if( this != &lst )
        {
            clear();
            for( Node* cur = lst.head; cur != 0; cur = cur->next )
                push_back( cur->data );
        }
        return *this;
    }

    void push_front( const MyType& mt )
    {
        if( len )
            head = new Node( mt, head );
        else
            tail = head = new Node( mt );
        ++len;
    }
    void push_back( const MyType& mt )
    {
        if( len )
        {
            tail->next = new Node( mt );
            tail = tail->next;
        }
        else
            tail = head = new Node( …
David W 131 Practically a Posting Shark

@tinstaafl, I aways appreciate your insights, and was wondering about the syntax of using ...

'auto'

in C++ 11

with the 'map' container ...

(and in the context of the OP, I was pleasently surprised to see that C++ 11 'knows' the size of arrays.)

This is the syntax that I found to work ok:

// map_test.cpp //

// compile with C++11 or newer compiler ... //

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <map>


int main()
{
    using std::cout; using std::string; using std::setw;
    using std::vector; using std::map;

    vector< string > names =
    { "sam", "peter", "joe", "joe", "peter" };

    map< string, int > mapNames;

    for( auto &n : names ) ++ mapNames[n]  ;



    cout << "COUNT, NAME\n";

    for( auto &n : mapNames )
        cout << setw(5) << n.second << ", " << n.first << '\n';



    cout << "\nNow doing an other way, traversing the same names ...\n\n";

    const char* names2[] = { "sam", "peter", "joe", "joe", "peter" };

    for( auto n : names2 ) ++ mapNames[n] ;

    for( auto &n : mapNames )
        cout << setw(5) << n.second << ", " << n.first << '\n';
}
David W 131 Practically a Posting Shark

Thank you, @deceptikon, for that update ...

The clause for omitting a return from main was added in C99 and retained in C11.

I was not aware of that, so thank you very much for updating me there.

(When I code in C, my habit has been to code to the old C89/C90 standard ... just to keep in practice there ... and it seems a lot of 'C beginning student code' ... still needs to conform to that old C89/C90 standard, also.)

David W 131 Practically a Posting Shark

Oops ... (some) typos above fixed now,
please see this 'fix' below:

bool more() // defaults to yes, more //
{
    cout << "More (y/n) ? " << flush;
    string reply;
    getline(cin, reply);
    if(reply.size() > 0 && tolower(reply[0]) == 'n')
        return false;
    // else ...
    return true;
}

There are other typos ...

For an example of a critical one,
a comma is missing in the array above,

a 'non-lethal' typo,
'quantity' is mispelled above.

a 'lethal' ...
float getTotal() const; // what is wrong with ; here?

David W 131 Practically a Posting Shark

I'm also now thinking ... a very good case could be made, for 'being lazy' ... by NOT keeping up with modern trends in C++ coding, and thus NOT using new coding tools to save your employers time and money :)

Unless that is, he/she is getting paid for your hours worked ...

and thus is ok with you 'padding' the hours ...

coding in unnessary things,

that the compilers are now designed to do for you :)))