David W 131 Practically a Posting Shark

Firstly, you may like to note that you mentioned using a vector of characters, but your code uses C++ strings, which is probably what you really meant to say?

Also, you need to lean to break up your program into 'jobs' ... and each job can be called by coding a function to do that specific job, then calling the function to execute that job at the appropriate place in the logic flow of your program.

Using descriptive function names, will help to self-document the logic flow of your program.

The following example may help you to see this:

// compareStrings.cpp //  // 2017-10-07 //

#include <iostream>
#include <sstream>
#include <string>
#include <cctype>

bool match( const std::string& a, const std::string& b, unsigned numChars )
{
    if( a.size() >= numChars && b.size() >= numChars )
    {
        for( unsigned i = 0; i < numChars; ++ i )
        {
            if( a[i] != b[i] ) return false;
        }
        // if reach here ...
        return true;
    }
    // if reach here ...
    std::cout << "Either '" << a << "'and/or '"
              << b << "' had less than " << numChars << " characters, so ...\n";
    return false;
}

std::string takeInString( const std::string& msg )
{
    std::cout << msg;
    std::string line;
    getline( std::cin, line );
    return line;
}

char takeInChr( const std::string& msg )
{
    std::string reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}

bool more( const std::string& text )
{
    if( tolower( takeInChr( "More " …
rproffitt commented: Call your things by names that make sense is always a good idea. +12
David W 131 Practically a Posting Shark

Also ... in C++ you usually do NOT want redundant parameters in a class!

For example, in a circle, if you know one of: radius, diameter, circumference, area
you can calculate all the other ...

And note that PI (pi) is a constant value defined as the ratio of the circumference of any circle to its diameter,

You may like to see this demo code that also loops until
the user inputs valid numeric input
and also
as long as more() returns true.

// test_class_Circle.cpp //  // 2017-07-30 //

// you had ...

/*
#include "stdafx.h"
#include <iostream>
using namespace std;

class Circle
{
public:
    Circle(double radius, double diameter, double circumference);
    double pi = 3.14;
    double radius = 0;
    double diameter = radius * 2;
    double circumference = 2 * pi * radius;
    double pi * radius * radius;
};

void main()
{
    cout << "enter radius radius" << endl;
    cin << Circle.radius;
    cout << Circle.diameter;
    cout << Circle.circumference;
    cout << Circle.area;
    system("pause");
}
*/

// This is a nice student way it could/should be done in C++ //

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

const double PI = acos(-1.0 );

class Circle
{
private:
    double radius;
public:
    // default ctor...
    Circle() : radius(0) {}
    // ctor with passed in radius ...
    Circle( double radius ) : radius(radius) {}

    double get_radius() const { return radius; }
    double get_diameter() const { return radius * 2; }
    double get_circumference() const { return 2.0 * …
David W 131 Practically a Posting Shark

Is there a clue in the Dani user name that has a C++ in it, as in:

Linzi c++

Maybe it's some kind of generic code ?

So ... to answer the request about coding an input request:

int radius = takeInInt( "Enter your desired radius: " ); // 'takeInInt' is user defined/coded //

You could then put all this code into some function, say we name it: getVolume();

then you could code a big main loop like this:

do
{
    getVolume();
}
while( more() );

Oh .. you also need to code for the function more, before you can call it in your C++ or C program.

But ... if you are looking for a nice language to start your coding of this little programming problem ... you will appreciate coding it easily, in Python.

David W 131 Practically a Posting Shark

And ... If you prefer to use private data members in your Java classes, you could sub in the below three classes (files) where appropriate ...

public class Customer
{
    private static Console con = new Console();

    private int number = 0;
    private String name = "";

    public int getNumber()  { return number; }
    public String getName() { return name; }

    public void takeInInfo()
    {
        number = con.getInt(  "Enter customer number : " );
        name = con.getString( "Enter customer name   : " ).toUpperCase();
    }
}

And ...

public class Item
{
    private static Console con = new Console();

    private String type = "";
    private int quantity = 0;
    private double price = 0.0;

    public double extended() { return quantity * price; }

    public void takeInInfo()
    {
        type = con.getString(  "Enter type     : " );
        quantity = con.getInt( "Enter quantity : " );
        price = con.getDouble( "Enter price    : " );
    }
}

And ...

 public class Invoice
{  
    private static final double  DISCOUNT_BEGINS = 500.00; 
    private static final double  DISCOUNT_RATE   = 0.05;
    private static final double  NET_TAX_RATE    = 0.0825;

    private static String HEADER = "A NEW CUSTOMER INVOICE BEGINS ...";

    // Note: these next two obj's get new values on each pass in loops below //
    private static Customer cust = new Customer();
    private static Item item     = new Item();

    public static void main(String[] args)
    {
        //Outer loop for Customer input ...
        do 
        {
            // Note: in the below format string, the %n means print a newline //
            System.out.format( …
David W 131 Practically a Posting Shark

Since you seem a little confuzzed ...

the following may help to jump-start your Java coding ...

Firstly ... recall in Java we like to use classes ... but here I am using classes more like we use a C++ struct ... this is to make the coding simpler ...
(i.e. NO need here to code for getters )

So I borrowed and EDITED a bit the Console class from the other program I referred you to earlier ...

So in the first file called: "Console.java", you could use these input methods ...

import java.util.Scanner;

public class Console {

    private static Scanner sc = new Scanner(System.in);

    public static String getString(String prompt) {
        System.out.print(prompt);
        String s = sc.nextLine();
        return s;
    }

    public static int getInt(String prompt) {
        int i = 0;
        while (true) {
            System.out.print(prompt);
            try {
                i = Integer.parseInt(sc.nextLine());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error! Invalid integer. Try again.");
            }
        }
        return i;
    }

    public static double getDouble(String prompt) {
        double d = 0;
        while (true) {
            System.out.print(prompt);
            try {
                d = Double.parseDouble(sc.nextLine());
                break;
            } catch (NumberFormatException e) {
                System.out.println("Error! Invalid decimal. Try again.");
            }
        }
        return d;
    }
}

Then you could use these next two classes (each file name is the same as the class name with a .java at the end of the file name as per this: 'FileName.java':

 class Customer
{
    static Console con = new Console();

    int number = 0;
    String name = "";

    void takeInInfo()
    {
        number = con.getInt(  "Enter customer …
David W 131 Practically a Posting Shark

Maybe you want this?

while(getline(infile,substance[index],','))
{
    // getline(infile,substance[index],','); // done above //
    infile >> molWeight[index];
}

It is hard to tell what you want without some sample data file.

Perhaps the following example of reading a csv data file might help?

// fileReadWriteStudent_csv.cpp //

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

using namespace std;


const char* FILE_IN  = "Students_in_csv.txt";
/*
1001,Joe Toe Smith,33
1002,Ann Fran Books,44
1003,Harry Larry Sanders,11
*/
const char* FILE_OUT = "Students_adjusted.txt";

const int ADJUST = 50;


struct Student
{
    int id;
    string name;
    int score;

    istream& takeIn( istream& is )
    {
        string line;
        getline(is, line);
        istringstream iss( line ); // form iss obj. from line //
        char comma;
        iss >> id >> comma;
        getline( iss, name, ',' );
        iss >> score;

        return is;
    }

    void print( ostream& os ) const
    {
        int score_adj = score + ADJUST;
        if( score_adj > 100 ) score_adj = 100;
        os << setw(4) << setfill('0') << id  << ' '
           << setfill('.') << left << setw(30) << name << ' '
           << setfill(' ') << right << setw(3) << score_adj << endl;
    }

} ;



int main()
{
    ifstream fin( FILE_IN );
    ofstream fout( FILE_OUT );
    if( fin && fout )
    {
        Student stud;
        while( stud.takeIn( fin ) )
        {
            // do any processing here that you wish on this 'word' ... for example
            // just print it to screen and to file, each 'word' on a new line …
David W 131 Practically a Posting Shark

Note the words 'local' ... and 'copy' (of pointer/address) ...

This is the crux of your problem here.

int a = 1, b = 2;
int* x = &a;
int* y = x; /* an alias (i.e. a copy) of x */
x = &b;
/* what is *y = ? now */
/* what is *x = ? now */

Compile and run ...

#include <stdio.h>

int main()
{
    int a = 1, b = 2;
    int* x = &a;
    int* y = x; /* an alias (i.e. a copy) of x */
    x = &b;

    /* what is *y = ? now */
    printf( "*y = %d ", *y );

    /* what is *x = ? now */
    printf( "*x = %d", *x );

    return 0;
}
David W 131 Practically a Posting Shark

Ok ... let's suppose that you have had time by now to write and try out some 'debugging' type code ... as per my suggestion above ... but maybe ... you still fail to 'see' the answer to your problem ... and the solution to the very commom and related problem?

What follows is a demo of two ways to handle this (related) problem ... the problem of changing addresses inside functions ... addresses held by passed in pointers ... and the solution to the problem of how to reflect, in the calling scope, this address update.

/* pointer_demo.3 */

#include <stdio.h>


int q_global = 10;

int* func1( int* address_copy ); /* returns any updates to address inside fumction */

void func2( int** pp ); /* a pointer to a pointer */




int main()
{
    /* method 1 */
    int r = 30;
    int* r_address = &r;
    puts( "Method 1 ..." );

    printf( "q_global = %d, &q_global = %p\n", q_global, (void*) &q_global );
    printf( "r = %d, r_address = %p\n", r,  (void*)r_address );

    r_address = func1( r_address );

    printf( "%d\n", *r_address );
    printf( "r = %d, r_address = %p\n", r,  (void*)r_address );


    /* method 2 */
    puts( "\nMethod 2 ..." );
    r = 30;
    r_address = &r;

    printf( "q_global = %d, &q_global = %p\n", q_global, (void*) &q_global );
    printf( "r = %d, r_address = %p\n", r,  (void*)r_address );

    func2( &r_address ); /* NOTE: here we pass in the address of the pointer variable r_address */

    printf( "%d\n", *r_address );
    printf( …
David W 131 Practically a Posting Shark

Since this was your first post, please be advised that ...

you will need to firstly post the code that you, yourself, have coded ... and tried,

also include a full and exact copy of the assignment you were given,

also include all design specifications and limitations, if any were added.

Then, we may be able to see where you are having difficulty and how to best help you.

David W 131 Practically a Posting Shark

You really have two distinct problems that are easiest/best to be each solved on their own:

1) code a linked list.
2) code a contact list using a linked list as a container.

You might like to look at the next two links to see this division of labour:

http://developers-heaven.net/forum/index.php/topic,2606.0.html
Steps to a C++ template class List

http://developers-heaven.net/forum/index.php/topic,2586.0.html
Class Student using STL list

David W 131 Practically a Posting Shark

We really can not help you on a free public forum if the code you present has copywrite attached ... how can we copy/edit it then?

Also ... over 1000 lines of code ? If you really need help, isolate the few lines of code that you need help to implement ... make a minimal test program to test that code out ... and then we may be able to help ... if it is your original code ... and if it does not have copywrite to it?

David W 131 Practically a Posting Shark

You seem to be using C++ ... so use C++ string ...
(and this question should then be in the C++ forum.)

Another way to get the string you need is to use an array of strings (a table) ...
See the example below:

// return_a_string.cpp//

#include <iostream>
#include <iomanip> // re. setw
#include <string>  // use C++ string in C++ //
#include <sstream> // re. stringstream objects //
#include <cctype> // re. tolower //

using namespace std;


const string DELIVERY[] =
{
    "UNKOWN", "BlueDart", "FedEx", "Delhivery", "DTDC/FirstFlight",
    "Ecom Express", "India Post", "ATS", "Ekart", "Aramex"
} ;
const int NUM_DELIVERY_TYPES = sizeof DELIVERY / sizeof *DELIVERY;

const string CHOICES[] =
{
    "", "Baby & Mom", "Books & Magazines", "Cameras & Optics", "Automotive",
    "stringity", "Clothing & Accessories", "Coins & Notes", "Collectibles",
    "Fitness & Sports", "Fragrances, Beauty & Health", "Fun Stuff", "Games & Accessories",
    "Home and Living", "Home & Kitchen Appliances", "Jewellery & Precious Coins", "Kitchen & Dining",
    "Laptops & Computer Peripherals", "LCD, LED & Televisions", "Memory Cards, Pen Drives & HDD", "Mobile Accessories",
    "Mobile Phones", "Gaming Consoles", "Movies & Music",  "Musical Instruments", "Services & Real Estate",
    "Shoes", "Stamps", "Stationery & Office Supplies", "Tablets & Accessories",
    "Hardware & Electricals", "Toys, Games & School Supplies", "Travel", "Watches", "Warranty Services", "Wearable Devices",
    "Audio & Home Entertainment", "Everything Else"
} ;
const int NUM_CHOICES = sizeof CHOICES / sizeof *CHOICES;


template< typename T >
T takeIn( const string& msg )
{
    T val;
    while( true )
    {
        cout << msg << flush;
        if( …
David W 131 Practically a Posting Shark

There are few things about your style of coding that could be improved:

/* use Global const (in C use #define) instead of 'magic numbers' */
#define MAX_LEN 31 /* pick numbers that give multiplies of 4 (or 8) bytes */ 

typedef struct
{
    char name[MAX_LEN+1], /* recall need space for terminal 0 */
         surname[MAX_LEN+1];
    int number;

} Player ; /* Use Cap then small case here */


typedef struct
{
    char nameofteam[MAX_LEN+1];
    int numberofplayers;
    Player* players;

} Team ;

/* 
Note: usually it is better to pass in data records by passing the address.
 */
void pr_replaces_numout( Team* tm, const Player* pr, int numout )
{
    int i;
    for( i = 0; i < tm->numberofplayers; ++ i )
    {
        if( tm->players[i].number == numout )
        {
            strcpy( tm->players[i].name, pr->name );
            strcpy( tm->players[i].surname, pr->surname );
            tm->players[i].number = pr->number;
            break;
        }
    }
}
David W 131 Practically a Posting Shark

There are several steps to the final solution of your problem ...

The first step that I would suggest you take would be to get some test data,
perhaps like this ... to get a bin file to test the rest of your code:

/* spiltInto2Files.c */

#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* strcmp */

#define MAX_STR_LEN 19
#define FORMAT_STR_IN " %19s %19s %19s %19s %lf"
#define FORMAT_STR_OUT "%-19s %-19s %-19s %-19s %10.2f\n"


const char* START_TXT = "start.txt";
/*
12345 Samuels Joe Prof 60000
12348 Plummer Bob Assist 30000
12347 Anderson Kim Assist 25000
12344 Davidson George Prof 110000
12346 Bowers Ann Assist 20000
*/

const char* TEST_BIN = "test.bin";

const char* PROF_FILE   = "prof.txt";
const char* ASSIST_FILE = "assist.txt";


typedef struct
{
   char id[MAX_STR_LEN+1],
        surname[MAX_STR_LEN+1],
        name[MAX_STR_LEN+1],
        title[MAX_STR_LEN+1];
   double salary;

} Employee ;

int create_bin_file( const char* fname_in, const char* fname_out)
{
    FILE* fin  = fopen( fname_in, "r" );
    FILE* fout = fopen( fname_out, "wb" );
    if( fin && fout )
    {
        char buf[128];
        Employee tmp;
        while( fgets( buf, sizeof buf, fin ) )
        {
            if( sscanf( buf, FORMAT_STR_IN, tmp.id, tmp.surname, tmp.name, tmp.title, &tmp.salary ) != 5 )
                return 0;;
            /* size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream ); */
            if( fwrite( (char*)&tmp, sizeof(Employee), 1, fout ) != 1 )
                return 0;
        }
        fclose( fout );
        fclose( fin );
        return 1;
    }
    /* else */
    printf( "Error opening files ...\n" );
    return 0;
}

After that, you should test that …

David W 131 Practically a Posting Shark

All you need to do is change the print function to a ....
get and fill array function ...
like this:

void get_positions( const int* ary, int size, int val, int* pos_ary )
{
    int i, j = 0;
    for( i = 0; i < size; ++ i )
    {
        if( ary[i] == val )
            pos_ary[j++] = i;
    }
}

Then, you could update the main function, to be like this:

int main()
{
    int arr[] = { 14, 10, 2, 1, 14, 1, 10, 14, 14, 2, 3, 4, 14, 14, 1, 4, 14, 14 };
    int size = sizeof arr / sizeof *arr ;
    int i, i_mc, size_vc_ary = 0;

    ValCount* vc_ary = malloc( sizeof(ValCount) * size );

    if( vc_ary )
    {
        int* pos_ary;

        for( i = 0; i < size; ++ i )
            size_vc_ary = update( vc_ary, size_vc_ary, arr[i] );

        i_mc = get_i_of_max_count( vc_ary, size_vc_ary );

        printf( "The most frequent value was %d and it occured %d times.\n",
                vc_ary[i_mc].val, vc_ary[i_mc].count );
        printf( "The value %d occured at positions: ", vc_ary[i_mc].val );

        pos_ary = malloc(sizeof(int) * vc_ary[i_mc].count );
        if( pos_ary )
        {
            get_positions( arr, size, vc_ary[i_mc].val, pos_ary );

            for( i = 0; i < vc_ary[i_mc].count; ++ i )
            {
                printf( "%d ", pos_ary[i] );
            }
            /* free up all dynamic memory when done with it */
            free( pos_ary );
        }

        /* free up all dynamic memory when done with it */
        free( vc_ary );
    }

    printf( "\n\nPress 'Enter' to continue/exit ... " );
    fflush( stdout );
    return 0;
}
David W 131 Practically a Posting Shark

A very common beginner level simulation is 'rolling a die' or 'rolling a pair of dice', using rand() to get random values in the range 1.. 6

See what you can do coding something like a guessing game with that idea firstly.

alfadil ahmed commented: thank you very much indeed , I appreciate your help. +0
David W 131 Practically a Posting Shark

You could form a string and print the reversed string ...
(i.e. similar to using a 'stack' to unwind the recursive calls)
like this:

#include <stdio.h>

/*
    Write an iterative function char* conversion(unsigned int num, int base),
    that converts an integer num into any base (base <=10).

    How to transform the following recursive function conversion() 
    into (an) iterative:
*/


void conversion( unsigned num, unsigned base )
{
    if( num / base )
        conversion( num / base, base );
    printf( "%u", num % base);
}

/* assumes number is greater than base ... */
void conversion_iterative( unsigned num, unsigned base )
{
    char buf[64]; /* make extra large enough to hold digits */
    int i = 0, size = 0;
    while( num / base )
    {
        buf[size++] = num % base + '0';
        num /= base;
    }
    buf[size++] = num % base + '0';
    buf[size] = 0; /* '\0' terminate */

    /* now reverse string */
    --size;
    while( i < size )
    {
        char tmp = buf[i];
        buf[i] = buf[size];
        buf[size] = tmp;
        ++i, --size;
    }
    printf( "%s", buf );
}



int main()
{
    unsigned num, base;
    printf( "num = " );
    if( scanf( "%u", &num ) == 1 && getchar() == '\n' )
    {
        do
        {
            printf( "base = " );
            if( scanf( "%u", &base ) != 1 )
            {
                printf( "Numbers only here please in range 2..10\n" );
                while( getchar() == '\n' ); /* flush 'stdin' ... */
            }
        }
        while( base < 2 || base > 10 );

        conversion( num, base );
        putchar( '\n' );
        conversion_iterative( num, base );
    }


    return 0;
}
David W 131 Practically a Posting Shark

I would use a struct (with a typedef) to create a data record to track the frequencies of each value in the int array.

Maybe something like this ...

Firstly:

/* most_frequent.c */


#include <stdio.h>
#include <stdlib.h> /* re. malloc */

typedef struct
{
    int val;
    int count;
} ValCount ;

Then some functions:

int update( ValCount* ary, int size, int val )
{
    int i, found = 0;
    for( i = 0; i < size; ++i )
    {
        if( ary[i].val == val )
        {
            ++ary[i].count;
            found = 1;
            break;
        }
    }
    if( !found )
    {
        ValCount tmp;
        tmp.val = val;
        tmp.count = 1;
        ary[size] = tmp;
        ++size;
    }
    return size;
}

int get_i_of_max_count( const ValCount* ary, int size )
{
    int i, i_mc = 0;
    for( i = 1; i < size; ++ i )
    {
        if( ary[i].count > ary[i_mc].count ) i_mc = i;
    }
    return i_mc;
}


void print_positions( const int* ary, int size, int val )
{
    int i;
    for( i = 0; i < size; ++ i )
    {
        if( ary[i] == val ) printf( "%d ", i );
    }
}

Then the main function could be like this:

int main()
{
    int arr[] = { 14, 10, 2, 1, 14, 1, 10, 14, 14, 2, 3, 4, 14, 14, 1, 4, 14, 14 };
    int size = sizeof arr / sizeof *arr ;
    int i, i_mc, size_vc_ary = 0;

    ValCount* vc_ary = malloc( sizeof(ValCount) * size );

    if( vc_ary )
    {
        for( i …
David W 131 Practically a Posting Shark

As Dani's own @rubberman has indicated ... the char '0' has the ASCII int value of 48

But you do not need to worry about memorizing that (48) value,
as you can convert form char to int
for the digits 0...9
very easily like this:

/* problem3.c */

#include <stdio.h>

int main()
{
    const int ary[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    const int size = sizeof ary / sizeof *ary;
    int i;
    char buf[256];
    const char* numStr = "123456789";
    const char* p = numStr;

    int sum = 0;
    while( *p != 0 )
    {
        sum += *p - '0';
        ++ p;
    }
    printf( "The sum for 1 to 9 is %d\n", sum );

    for( i = 0; i < size; ++ i )
    {
        buf[i] = i + '1'; /* OR: i+1 + '0'; */
    }
    buf[size] = 0; /* terminate C string with '\0' char ...*/

    printf( "\nHere are the digits 1..9 placed into a C string: %s\n", buf );

    fputs( "\nPress 'Enter' to continue.exit ... ", stdout );
    fflush( stdout );
    getchar();
    return 0;
}
David W 131 Practically a Posting Shark

If you will Google "C stack" ... you may be surprised how much is at your finger tips but you never looked to see?

A 'stack' is a 'last-in-first-out' (LIFO) data structure that has many uses in programming.

So ... say you have the word "first" and you have a 'stack' to hold characters ...

and if first you put on the stack the char ...
'f'
then 'i'
then 'r'
then 's'
then 't'

Now if you pop the letters from the top of the stack and print them as you pop them, you will print:

tsrif

if you print them all, one after the other, on the same line.

There are many ways one might implement a stack.

One might be to use an array ...
and to advance a pointer into the array
after every element is 'pushed' onto the stack,
then to retreat the pointer after every pop.

Another common way could be
to use a linked list
and push_front to put new elements on the stack ...
then to pop_front ... to pop them off.

If you need help coding a linked-list in C,
you might like to start by looking at several examples linked here:
http://developers-heaven.net/forum/index.php/topic,2022.0.html

If you need to push 'words' onto a stack of 'words' ...
you could use the ClistOfString.h file (and the other files it uses freely available there) to use a Clist of …

David W 131 Practically a Posting Shark

Firstly ...
please note that if you wish your code to be portable,
do not use <conio.h>

You can use a C struct and a typedef to create whatever data record you need.

typedef struct
{
    char* name;
    int id;
    int scores[5];

} Student;

And then in your main function ... get space to hold as many records as you need:

Student studs[100]; /* reserve space to hold 100 Student rec's */
campuzcrazyness commented: Thanks. +1
David W 131 Practically a Posting Shark

You could use some functions ... maybe something like this to start:

from turtle import *
from math import *

speed(5)

def rectangle( x, y, w, h ):
    up()
    goto( x, y )
    setheading(0)
    down()
    for repeat in range( 2 ):
        fd(w)
        left(90)
        fd(h)
        left(90)

def peak( x, y, w, h ):
    up()
    goto( x, y )
    down()
    goto(x+w/2, y+h)
    goto( x+w, y )

#HOUSE
rectangle( 100, 0, 200, 100 )
peak( 100, 100, 200, 60 )


def tree( x, y, w, h ):
    up()
    goto( x, y+h )
    down()
    setheading( -45 )
    for repeat in range(3):
        fd( .9*h/4/cos(45) )
        rt(180-45)
        fd( w/3 )
        left( 180-45 )
    up()
    goto( x, y+h )
    down()
    setheading( (45+180) )
    for repeat in range(3):
        fd( .9*h/4/cos(45) )
        left(180-45)
        fd( w/3 )
        right( 180-45 )
    setheading(0)
    fd(.9*w)
    rectangle(x-w/20, y, w/10, h/10 )

tree( -50, 0, 100, 160 )
tree( -250, 0, 100, 160 )
tree( -250, -200, 100, 140 )
tree( -50, -200, 80, 120 )
David W 131 Practically a Posting Shark

I would re-think what you are trying to do?

This example of a 'class Cube' may give you some ideas re. a simpler design.

example of a test main file:

// cube_test.cpp //


#include "cube.h"


int main()
{
    Cube cu( Point(0, 0, 0), 1 );
    cu.show();

    printf( "Press 'Enter' to continue/exit ... " ); fflush( stdout );
    getchar();
}

.h file:

// cube.h //

#ifndef CUBE_H
#define CUBE_H

#include <cstdio>

struct Point
{
    int x, y, z;

    Point( int x=0, int y=0, int z=0 ) : x(x), y(y), z(z) {}

    void print() const
    {
        printf( "(%d, %d, %d)\n", x, y, z );
    }
} ;


class Cube
{
public:
    Cube( const Point& pt, int cwidth );
    void show() const;
private:
    int width;
    Point corner[2][2][2];
} ;

#endif;

.cpp file:

// cube.cpp //

#include "Cube.h"


Cube::Cube( const Point& pt, int cwidth ) : width(cwidth)
{ 
    for( int ix = 0; ix < 2; ++ix )
    {
        for( int iy = 0; iy < 2; ++iy )
        {
            for( int iz = 0; iz < 2; ++iz )
                corner[ix][iy][iz] = Point( pt.x + ix*cwidth, pt.y + iy*cwidth, pt.z + iz*cwidth );
        }
    }
}

void Cube::show() const
{
    for( int ix = 0; ix < 2; ++ix )
    {
        for( int iy = 0; iy < 2; ++iy )
        {
            for( int iz = 0; iz < 2; ++iz )
            {
                corner[ix][iy][iz].print();
            }
        }
    }
}
David W 131 Practically a Posting Shark

How does an array variable indexing expression differ from an array definition size expression?

Recall arrays in C/C++ are 0 based ...

i.e. if 'n' slots ...

first index i is at i = 0

nth index i is at i = n-1

David W 131 Practically a Posting Shark

Take it in steps ... Firstly just read in the file and display it back ... Get that working before you add any other methods.

You may like to look here for some more ideas ...
http://developers-heaven.net/forum/index.php/topic,2019.0.html

David W 131 Practically a Posting Shark

Hi @rose_2,

Do you know how to code an "Hello World" type program in C++ ?

If you do, then you can prompt for input.

Then the next thing ... is to code to take in some number ...
and then to take in numbers in a loop and to sum them up.

There are actually many ways to code for this...
but a simple way is demo'd at the following link:

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

But code your own version of a solution for your problem ...
and if you get stuck,
then you will need to show us the code you have tried so far.

Then ... we can see how to help you.

David W 131 Practically a Posting Shark

An other way to approach your problem is to 'huffle the deck' before dealing it out ...

Take a look:

/* 52Cards.c */

/*
    You can find file "readline.h" at:
    http://developers-heaven.net/forum/index.php/topic,2580.msg2864.html#msg2864

    You can find file "Cvec.h" at:
    http://developers-heaven.net/forum/index.php/topic,2580.0.html

*/

#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 showCards( const Cvec* cards )
{
    int i;
    for( i = 0; i < cards->size;  )
    {
        printf( "%c%c  ", cards->ary[i].val, cards->ary[i].kind ) ;
        if( ++i % 13 == 0 ) putchar('\n'); …
JamesCherrill commented: Definitely the best approach +15
David W 131 Practically a Posting Shark

The code ? maybe ? something like this:

template< class T >
void tqkeInAndInsertItem( TreeClass< T >& tree )
{
    cout << "Enter item: ";
    T tmp;
    cin >> tmp; // MUST HAVE defined >> for type T //
    tree.insert( tmp );
    cout << "Item inserted:" << tmp; // MUST HAVE defined << for type T //
}
David W 131 Practically a Posting Shark

Do you know how to (start the) code for a C++ class?

Show us as much as you can ... (i.e. fill in your code for) :

#include <iostream>
// ...

class Teacher
{
public:
    // ...
private:
    // ...
} ;

class Student
{
    friend class Teacher;
public:
    // ...
private:
    // ...
} ;


int main()
{
    // ...
}
David W 131 Practically a Posting Shark

A next step might be to use functions to get valid input in a loop?

Also maybe use a struct tp hold the 'counts'?

Take a look:

// countPosNeg.cpp //  // 2015-0915 //

#include <iostream>

using namespace std;


struct Counts
{
    int pos, neg;

    // default ctor...
    Counts() : pos(0), neg(0) {}
} ;


int takeInInt( const char* msg )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
            break;
        else
        {
            cout << "Invalid input ... numbers only!\n";
            cin.clear(); // clear error flasgs
            cin.sync(); // 'flush' cin stream ...
        }
    }
    return val;
}

int takeInChr( const char* msg )
{
    cout << msg << flush;
    int c = cin.get();
    cin.sync();
    return c;
}

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




int main()
{
    Counts cts; // construct with default values //

    do
    {
        int i = takeInInt( "Enter an integer: " );
        if( i >= 0 ) ++cts.pos;
        else ++ cts.neg;
    }
    while( more() );

    cout << "Out of " << (cts.pos+cts.neg) << " numbers, you entered "
         << cts.pos << " positive and " << cts.neg << " negative.\n";

    takeInChr( "Press 'Enter' to exit ... " );
}
JamesCherrill commented: We need more code like this - real structure vs one endless block +15
David W 131 Practically a Posting Shark

You could start with some definitions like this:

const double EPSILON = 0.000001; /* change here to what you want */

/* define the function to integrate ... */
double f( const double x )
{
    return x*x - 3*x  + 2;
}

/* numerical method to get area inder curve of f(x) from x = beg to x = end ... */
double areaTraps( const double beg, const double end, const double dx )
{
    double x, area = 0;
    for( x = beg; x < end; x += dx )
        area +=  (f(x) + f(x+dx)) / 2.0 * dx;
    return area;
}

Then in main, you could do something like this:

double dx = 0.1;

/* get an initial approx. value for area_2 ... */
double area_2 =  areaTraps( 2, 8, dx ),
       area_1;

do
{
    area_1 = area_2; /* save copy of previous area estimate ... */
    dx /= 10;
    area_2 = areaTraps( 2, 8, dx ); /* get a closer estimate */
}
while( fabs( area_2 - area_1 ) > EPSILON ) ;

printf( "Area was %.6f and size of last 'dx' was %.16f ", area_2, dx );

getchar();
return 0;
ddanbe commented: Most helpfull +15
David W 131 Practically a Posting Shark

This code of yours:

string PK; // stands for primary key;
while ( getline( fin, line) && PK++ > 1);
PK = 98;

does NOT make any sense at all!

If PK is a C++ string,
then the default value (when constructed as you have coded)
is "", i.e. the empty string, and then this code:

PK++ makes NO sense at all!

But ...

PK += "Sam"; 
// this code makes sense, it 'concatenates' the string "Sam" 
// to the end of the empty string PK ... 
// so that PK then becomes "Sam" //

And then trying to compare a C++ string value to an int of value 1 ...
this reveals that you are really terribly mixed up,
and NOT understanding even C++ coding basics!

You need to start at the beginning and learn to program step by step.
(Study the 6 fast steps link I gave you previously ...)
There are many beginning C++ tutorials on line ...

Try this slower paced one:

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

Where did you get this problem of extracting data from source files structured as you have suggested ... to produce the particular extracted csv data file you seem to want?

But take a look ...
this is how one might code a solution ...
after your last 'hint' ...
about the way the data is structured in the input data file:

// fileReadWrite3.cpp //  // …
David W 131 Practically a Posting Shark

You really do not need to read the processed records into a vector ...

I would keep it simple ... something like this:

// fileReadWrite.cpp //

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>

using namespace std;

const char* FILE_IN  = "rawDataForExcel.txt";
const char* FILE_OUT = "selectedData.csv";

// example of 'in file'
/*
    AUG.02, 2015
    SMPH01 RPMM 020000
    AAXX 02001
    98132 31462 21101 10293 20264 40145 53020 70540 82100 33302 20255 56399 59004 82817 ='01
      rh93/76 rmks 255 2am, fe.
    98133 31467 20902 10300 20270 40109 5//// 70544 82200 222// 20501 33301 20255 56299 58002
     82818 MJ. RMK.RH=90/80 MIN.=25.5 8AM
    98134 32465 21002 10287 20253 39928 40114 53013 82200 33301 20250 56999 58002 82819 ='12
      max=305@0600z min=250@1800z rh=87/79 MP
    98222 31570 10201 10284 20242 40114 51007 70544 81200 33301 20249 56999 59002 81820 ='01
      occurance of min. Temp. 2210z ca
*/

struct CSV
{
   string ary[10]; // A,B,C,D,E,F,G,H,I,J; //

   // returns 0, or 1 if NEXT line is read in already //
   int extract( istream& fin, const string& str )
   {
       istringstream iss( str );
       string tmp;
       iss >> tmp;
       ary[0] = tmp.substr(0,2);
       ary[1] = tmp.substr(2);

       iss >> tmp;
       ary[2] = tmp.substr(0,1);
       ary[3] = tmp.substr(1,3);
       ary[4] = ary[5] = ary[6] = ary[7] = ary[8] = ary[9] = "x";

       for( int i = 0; i < 6; ++ i )
            iss >> tmp; // skip over 3,4,5,6,7 and read 8
       ary[4] = tmp.substr(0,1);
       ary[5] = tmp.substr(1,3);

       iss >> tmp;
       ary[6] = tmp.substr(0,1);
       ary[7] = tmp.substr(1,3);

       while( iss >> tmp && …
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

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

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

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

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

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

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

Further to the above Posting Pro @ Schol-R-LEA comments ...

and since ... the meaning to be helpful @ Aditya_13 ...
posted his first code here ...

please also note these comments that are also meant to be helpful to, now especially, @ Aditya_13 ...

Please take a look at the revisions and comments in this revision of the code posted, that uses some of the power tools of C++ ... power tools like over-loading operators and vector containers ... and of course ... the general tool of breaking up a problem into steps ... each step having its own function

The goal here was not to as brief as possible, but rather to make clearer the steps to a solution ...

// print_pattern.cpp //

// these are old style //
//#include<iostream.h>
//#include<conio.h> // do NOT use if you wish code to be portable //
//#include<math.h>

#include <iostream>
#include <string>
#include <vector>
#include <cmath>

using namespace std;

#define myDebug 0 // toggle zero & one ... to turn off & on //


/////////////////////////////////////////////
// some helpful student utility functions //
int takeInInt( const char* msg);
int takeInChr( const char* msg );
bool more();
/////////////////////////////////////////////


/*
If N=4 the code should print the following pattern.
                                 1*2*3*4*17*18*19*20
                                 --5*6*7*14*15*16
                                 ----8*9*12*13
                                 ------10*11
Again if N=5 the code should print
                                 1*2*3*4*5*26*27*28*29*30
                                 --6*7*8*9*22*23*24*25
                                 ----10*11*12*19*20*21
                                 ------13*14*17*18
                                 --------15*16
For N=2  the pattern will be
                                 1*2*5*6
                                 --3*4

*/

// from the pattern above, it seems that ...
// if n = 4, 4*5 = 20 numbers are …
David W 131 Practically a Posting Shark

Note: There are many way to design a solution ...

Here is just one simple way ...

and a shell program that should get you started:

// cal_shell.cpp //


#include <iostream>

using namespace std;

// your functions go here ...??

double add( double a, double b )
{
    return a + b;
}

 double sub( double a, double b )
{
    return a - b;
}

// ... the rest of your functions go here //



int main() 
{
    // print out an intro...

    // prompt and take in the op requested ...add, sub, etc...
    cout << "Which op ... Enter + or - or ... ";
    char op = 0;
    cin >> op;

    double a = 0.0, b = 0.0, c = 0.0; // get some doubles

    // now prompt and take into 'a' annd 'b' valid doubles

    switch( op )
    {
        case '+' : c = add( a, b ); break;
        case '-' : c = sub( a, b ); break;

        // ... rest goes here ...//



        default:
            cout << op << " is NOT implemented here yet ...\n";
    }

    cout << "for the binary op " << op << " on " << a << " and " << b
         << ", the result returned was " << c << endl;
    cout << "All done ... press 'Enter' to cobtinue/exit ... " << flush;
    cin.get();
}
David W 131 Practically a Posting Shark

If one apple costs 65 cents, how much will n apples cost?

Do you know how to multiply n*65 for all (positive integer) values of n?

David W 131 Practically a Posting Shark

If the pattern holds ( as per @ddanbe )...

you might like to try parsing, using the power of C++ stringstream,
something like this ...

// getFileDataParsed.cpp //

/*
    I have a text file that represents a book ,
    this first line of it for example is:

    P.G. Wodehouse, "Heavy Weather 1" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
    P.G. Wodehouse, "Heavy Weather 2" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
    P.G. Wodehouse, "Heavy Weather 3" (336 pp.) [PH.411 AVAILABLE FOR LENDING]
    P.G. Wodehouse, "Heavy Weather 4" (336 pp.) [PH.411 AVAILABLE FOR LENDING]

    So there is:
    authors name,
    title,
    number of pages
    and if the book is available.

    As they are not all seperayed by a comma,
    how can I read this file and store them in appropriate arrays ?

*/

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>

using namespace std;


const char* FILE_IN  = "books.txt";

// file line structure ...
// P.G. Wodehouse, "Heavy Weather" (336 pp.) [PH.409 AVAILABLE FOR LENDING]
struct Book
{
    string author;
    string title;
    string pages;
    string available;

    friend ostream& operator << ( ostream& os, const Book& b )
    {
        return os << b.author << ", " << b.title << ", "
                  << b.pages << ", " << b.available;
    }
} ;

bool takeInFileLine( istream& fin, Book& b )
{
    string line;
    if( getline( fin, line ) )
    {
        istringstream iss(line); // construct istringstream obj 'iss'
        getline( iss, b.author, ',' );

        string skip;
        getline( iss, skip, '"' );
        getline( iss, b.title, '"' …
ddanbe commented: Nice. +15
David W 131 Practically a Posting Shark

You also might like to see that using classes some times just adds code bloat.

Take a look (no classes) ...

// test_invalid_time_simple.cpp //


#include <iostream>
#include <iomanip> // re. setw, setfill
#include <string>
#include <cctype> // re. toupper


using namespace std;

void print24HourTime(int hr, int min, int sec, const string& );


// used here to take in valid numbers //

int takeInInt( const string& msg, int min, int max,
               const string& errmsg = "\nIntegers only please ...\n\n" )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
        {
            if( val >= min && val <= max ) break;
            //else ... if reach here ...
            cout << "Valid input range here is: " << min << ".." << max << "\n";
        }
        else
        {
            cout << errmsg;
            cin.clear(); // clear error flasgs
            cin.sync(); // 'flush' cin stream ...
        }
    }
    return val;
}

int takeInChr( const char* msg )
{
    cout << msg << flush;
    int c = cin.get();
    cin.sync(); // 'flush' cin stream
    return c;
}
bool more()
{
    int c = takeInChr( "More (y/n) ? " );
    if( c == 'n' || c == 'N' ) return false;
    // else ...
    return true;
}



int main ()
{
    do
    {
        string str;
        for( ; ; )
        {
            // do this part firstly ...
            // so can see that following hr is AM/PM //
            cout << "Enter AM or PM: ";
            cin >> str;
            cin.sync(); // …
David W 131 Practically a Posting Shark

Please see the comments at the end of your other similar post.

Those comments also apply here.

Please start fresh with ONE program and indicate where you think it may have some issues ... Also describe what the program is supposed to do.

Please take some time to look at other requests for help.

That will give you a better idea how to actually get the help you would like.

David W 131 Practically a Posting Shark

Which ...

Your life ?

Your programming ?

If you do not yet know much about programming ...

And if programming really is 'your life' ...

Then ... there's still, (but maybe just a little), time to learn how to live :)