David W 131 Practically a Posting Shark

As Dani's @ tinstaafl suggests ...

firstly ...

to get a design for just simple addition (of large int's of any size) to work,

you could use some functions to read in dynamic C strings of any size, maybe something like this:

Note that file "readLIne2.h" is available here:

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

/* add_dynamic_Cstrings.c */

#include "readLine2.h"



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

int is_valid( const char* str )
{
    while( *str )
    {
        if( *str < '0' || *str > '9' ) return 0;
        ++str;
    }
    return 1;
}


char* add( const char* a, unsigned len_a, const char* b, unsigned len_b, unsigned* len_c )
{
    char* c;
    int i, j;
    int overflow = 0;
    if( len_a >= len_b )
    {
        c = newMem( len_a+1 );
        c[len_a] = 0;
        for( i = len_a-1, j = len_b-1; j >= 0; --i, --j )
        {
            c[i] = a[i] + (b[j] - '0') + overflow;
            if( c[i] > '9' )
            {
                overflow = 1;
                c[i] -= 10;
            }
            else
            {
                overflow = 0;
            }
        }

        for( ; i >= 0; …
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

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

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

Look at the
'if ... else ...'
examples I gave you of different tests
and branching to different sections
by set / reset of 'flag' values
and see if you can code the exact solution that you wish?

If you get stuck ...
take a deep breath and 'think'

If ( condition is true ) do this
else do that

and try again ...
and if still stuck ... show the code you tried.

David W 131 Practically a Posting Shark

... but i missed the part where if a player rolls a 1,
the score should not be added to his total so it'll be the second players to roll.
i couldnt seem to get that command to work so far;
any idea?

Take a look at this demo ... that has ADDED EXTRA ROLLS for the 'computer' ...
if the 'computer rolls' certain values ...

/* rollDice2.c */  /* 2015-10-15 */

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

/*
     ... i missed the part where if a player rolls a 1,
     the score should not be added to his total
     so it'll be the second players to roll.
     i couldnt seem to get that command to work so far;
     any idea?

     BUT added here...
     if computer rolls 1, 3, 5 then computer rolls again ...
*/


/* prototypes for 3 handy utilities for many C student coding problems ... */

/* a simple student way to handle numeric input ...
   so program won't crash on bad input */
int takeInInt( const char* msg );
int takeInChr( const char* msg );
int more(); /* defaults to 'true'/'yes'/'1' ... unless 'n' or 'N' entered */



void showDice( int randNum );
void playGame();




int main() /* ******************************************* */
{
    do
    {
        playGame();
    }
    while( more() );

    return 0;
} /* **************************************************** */




void playGame()
{
    int gameTotal = 0, player = 0, computer = 0;
    char choice = 'p'; /* start with player, 'c' is for computer …
David W 131 Practically a Posting Shark

See example solutions to common beginner problems ...

1) take in valid int (with a prompt) so program won't crash
2) keep stdin flushed as you go ...
3) loop while more
4) takeInChr( withpromptStr ) to ease getting user choices

This demo may help you get started with clean working code ...

Note:
This demo does NOT entirely conform to the spec's you were given,
but is meant to help you get started.

/* rollDice.c */


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

void showDice( int randomNumber );
void playGame();


/* 3 handy utilities for many C student coding problems ... */
int takeInChr( const char* msg );
int more(); /* defaults to 'true'/'yes'/'1' ... unless 'n' or 'N' entered */
/* a simple student way to handle numeric input ...
   so program won't crash on bad input */
int takeInInt( const char* msg );




int main()
{
    do
    {
        playGame();
    }
    while( more() );

    return 0;
}





void playGame()
{
    int gameTotal = 0, player = 0, computer = 0;
    char choice = 'p'; /* start with player */

    srand( time(0) ); /* seed rand... */

    printf( "Welcome to the GAME of PIG ... \n\n" );

    gameTotal = takeInInt( "Enter the game total (for example 40): " );

    while( player < gameTotal && computer < gameTotal )
    {
        char roll;
        if( choice == 'p')
        {
            printf( "It's time for player ... \n" );
            do
            {
                roll = takeInChr( "Your choice roll or hold (r/h) …
David W 131 Practically a Posting Shark

You need to start coding, implementing the steps you were given ...

and then to show us the code you tried.

Re. the unclear graphic output part ... you will have to clear that up with the source.

David W 131 Practically a Posting Shark

Is your expanded problem to process multiple files in a folder?

If so, then you could modify the example to be looking for the (input) .txt file names from standard input ...

Then ... perhaps ....
write a batch file, (that calls that compiled modified program .exe file), to process ALL the .txt files in that folder ...

After each file was processed, it would yield/output the corresponding .csv file.

David W 131 Practically a Posting Shark

Test this code:

// call string constructor
string test2( "good better best" );

// call istringstream constructor
istringstream is( test2 );

string x,tmp,z;
// extract words/strings from is object
is >> x >> tmp >> z;

// show best good backwards
cout << z << ' ' << x;

David W 131 Practically a Posting Shark

Can you test this code ?

cout << "Enter 3 words separated by a space: ";
string a,b,c;
cin >> a >> b >> c;
cout << "You entered: " << a << " and " << b << " and " << c << endl;

Do you see how the extraction operator >> works with a cin stream?

istringstream objects are 'string streams' that via the extraction operator >> you can extract strings (or other types) from the stream.

David W 131 Practically a Posting Shark

In C++ you need to write your own code to print out the elements of an array ...

string test = "a BB ccc";
istringstream iss( test );
string str[3];
iss >> str[0] >> str[1] >> str[2];
// try this ... or code a loop
cout << str[0] << ',' << str[1] << ',' << str[2];

David W 131 Practically a Posting Shark

iss >> tmp; //is getting the next line?

No ... getting the next item.

string test = "a BB ccc";
istringstream iss( test );
string str[3];
iss >> str[0] >> str[1] >> str[2];

What do you think is now in each array element?

Can you write a short program to test this out ... and see what happens?

David W 131 Practically a Posting Shark

Did you try out the working code I provided?

Did you read the comments in the code and try to follow the steps?

If you do not take time to read the instructions and follow them ... then why should I take any more time with you?

David W 131 Practically a Posting Shark

You have already been given a working C++ example solution ... if you are really sincere about learning to program in C++, then ... you really do need to start at the beginning ... as I previously indicated, and even provided some links to help you to start.

For example ... if I were to attempt to talk to you about 'entropy' and the 2nd law of thermodynamics ... before you had studied 'energy' ( / 'heat' / 'work' ) and the 1st law of thermodynamics ... and 'the atomic nature' of all matter ... and the concept of 'temperature' ... would you be able to understand and solve problems that related to the concept of 'entropy' ?

http://developers-heaven.net/forum/index.php/topic,2587.msg3103.html#msg3103

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

Hint : the code might be a little simpler ... Read / discard 1st 3 lines ...
Then read a line ... and while exists next line and next line does not begin with "86" append to first line
Otherwise have first line of next rec... So process prev rec / 'extended line' and output the extracted data from this 'extended line'

David W 131 Practically a Posting Shark

NO!

This code: while( iss >> tmp && tmp.substr(0,3) != "333" ) ;
will be my reference I change 333 to 98, But I don't know where to put ...

NO!!! Leave that as is, since that was a part of your program data extraction specifications.

You need to think about what your program is supposed to do ... at each step ... and thus what edit(s) to make to example???

If you wish to process several files, each with the very same structure as the first, you could store the names in an array or an other C++ container like a vector, and then loop though each file name to process that file in turn ... while outputting processed data to files (or appending to a common output file if that was what you want.)

But ... get your code working perfectly ok for ONE representative example input file firstly !!!

David W 131 Practically a Posting Shark

The raw data file NEEDs to be 'massaged' to be regular to be read ok ...

IF these TWO lines are FIXED ...

It seems to be ALL read ok.

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
98223 31460 21101 10288 20259 40103 52013 70540 81205 33301 20240 56999 58006 81819 ='08
RH 96/47 TMIN 24.0 @ 5:30 A.M. TAFOR RPLI 0606 32006KT 9999 FEW019 TEMPO 0612 32008KT 9999 FEW019 SCT100 RPLI 020000Z 11002KT 9999 FEW019TCU 29/26 Q1010 NOSIG RMK A2982 TCU W RPG
98232 31570 30000 10279 20246 30109 40112 53009 70500 81100 222// 20100 33302 20262 56999
58007 81820 RH92/65 MAX.TEMP.33.0@0600Z MIN.TEMP.26.2@2200Z REM.SLIGHT SEA ET'09
98233 31568 50000 10253 20234 40121 53024 70540 83230 33302 20240 56999 58010 83820 85358='08
T MIN = 24.0 @ 5:40 AM, MX RH = 90%, MN RH = 65% MLT
98324 11462 40901 10280 20251 40107 53013 60084 70544 82211 33312 20244 56929 58006 70084 82816
83358 CC MIN TEMP 24.4 AT 2100
98325 31462 31601 10278 20252 40101 53011 70592 …
David W 131 Practically a Posting Shark

You need to have the file it is looking for ... available.

For ease of access, place the file to be read in the same folder as your compiled .exe (executable) file.

Did you NOT see the comments ?

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

The demo program, as above, IS looking for a file with the name:

"rawDataForExcel.txt"

So ...

Make sure a file with the above contents is there ... and called by that name!

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

Show us the code you have tried so far ... for this:

You could read/skip the first 2 lines ... Then read (in pairs of) 2 lines, skipping over that first line and parsing the 2nd line ... till done ... You could use stringstream objects to ease parsing each line of numbers you wish to parse ... (as per the examples at the link provided.)

David W 131 Practically a Posting Shark

To start, you could look at the file read/parse examples here:

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

David W 131 Practically a Posting Shark

You could read/skip the first 2 lines ...
Then read 2 lines, skipping over that first line and parsing the 2nd line ... till done

You could use stringstream objects to ease parsing each line of numbers you wish to parse.

David W 131 Practically a Posting Shark

Your code would be so much more C++ like if you could follow the example of Dani's @NathanOliver ...

But if you really have to use C strings and pointers to char ... (in a C++ program) ...you could try something like this:

// split2.cpp //

#include <iostream>
#include <sstream> // re . istringstream object //
#include <string>
#include <vector>

#include <cstdlib> // malloc
#include <cstring> // re. strchr, etc... //

using namespace std;

// using stringstream objects //
void toToks( vector< string >& v, const string& line, const char delimit = '|' )
{
    istringstream iss( line ); // construct istringstring object 'iss' from string 'line'
    string tmpTok;
    while( getline( iss, tmpTok, delimit ) )
        v.push_back( tmpTok ); // push back a copy //
}

// using strchr and passing in C strings //
void toToks2( vector< string >& v, const char* line, const char delimit = '|' )
{
    const char* p1 = strchr( line, delimit );

    while( p1 )
    {
        int size = p1-line;
        char* str = (char*) malloc (sizeof(char) * (size+1));
        if( !str )
        {
            cout << "\nAn ERROR occured in calling malloc ...\n\n";
            return;
        }
        strncpy( str, line, size );
        str[size] = 0;

        v.push_back( str ); // push back a C++ string copy //
        free( str );

        while( *p1 && *p1 == delimit ) ++ p1;
        if( *p1 )
        {
            line = p1;
            p1 = strchr( line, delimit );
        }
        else break;
    }
}



int main ()
{
    cout << "Preferred 'method 1' using …
David W 131 Practically a Posting Shark

You might like to use some C++ library functions to assist parsing a line ...

http://developers-heaven.net/forum/index.php/topic,2019.msg2682.html#msg2682

David W 131 Practically a Posting Shark

Write a batch file to handle this ... then call that batch file.

David W 131 Practically a Posting Shark

Your Dev IDE settings ...
permit your code to be compiled using one of these standards ...

ISO C90  <--- this is what I normally choose when compiling C student code
ISO C99 
ISO C++     <--- this ... or if needed then ...
ISO C++ 11  <--- this ... is what I normally choose for C++ student code
GNU C90
GNU C99
GNU C++
GNU C++ 11

One question ... explain the term C++ 11 which I set in my compiler ... it's purpose?

If you use features in your code that are NOT available in a 'lower standard',
then that code will NOT compile ...
until ...
you turn on the ability to compile that code that uses those 'higher' features.

For example,
if you used [ ] with a 'lambda function' in some C++ code and used the ISO C++ compiler setting ...
it would NOT compile ...
until you reset the compile setting to one of the C++ 11 compile settings

David W 131 Practically a Posting Shark

Since I have not heard further ... I presume you have 'the example' working ok?

Here is a little upgrade to demo the ease of editing that code to a 'template'.

// CStack.h //  // 2015-08-03 //


// use a C++ 11 (or newer) compiler //

#include <iostream>
#include <string>
#include <stdexcept>

// using namespace std;

class cInvalidStack : public std::exception
{
protected:
    std::string msg;
public:
    cInvalidStack( const std::string& msg = "" ) : msg(msg) {}
    virtual std::string& what() = 0;
} ;



class cInvalidPush : public cInvalidStack // throw if stack is full
{
public:
    cInvalidPush() : cInvalidStack( "Stack is full." ) {}
    std::string& what() { return msg; }
} ; 

class cInvalidPop: public cInvalidStack // throw if stack is empty
{
public:
    cInvalidPop():cInvalidStack( "Stack is empty." ) {}
    std::string& what() { return msg; }
} ;



template< typename T >
class CStack 
{
public:
    CStack (const size_t stackSize = 10 ); 
    ~CStack();

    // copy ctor...
    CStack( const CStack& cstk )
    {
        top = cstk.top;
        max_size = cstk.max_size;
        ptr_stk = new T[max_size];
        for( size_t i = 0; i < top; ++ i ) ptr_stk[i] = cstk.ptr_stk[i];
        for( size_t i = top; i < max_size; ++ i ) ptr_stk[i] = T();
    }
    // overloaded operator ==
    CStack& operator == ( const CStack& cstk )
    {
        if( this != &cstk )
        {
            delete ptr_stk;

            top = cstk.top;
            max_size = cstk.max_size;
            ptr_stk = new T[max_size];
            for( size_t i = 0; i < top; ++ i ) ptr_stk[i] = cstk.ptr_stk[i];
            for( size_t …
David W 131 Practically a Posting Shark

re. 2)
tools
compiler options
settings
code generation
compile width ... pointer width ... select 64 bit

re. 1)
tools
compiler options
settings
code generation
language standard ... select either C++ 11 option

And while your setting up your compiler turn on warnings (click on):
tools
compiler options
settings
code generation
warnings
select ... these 3 ... -Wall, -Wextra, -pedantic

David W 131 Practically a Posting Shark

With your Dev compiler ...

1) make sure you HAVE pre-set ... to compile as C++ 11

2) make sure the pointer width is 64 bit

3) make sure to compile with 64 bit release

Other settings than the above seem to be problematic with your Dev compiler

David W 131 Practically a Posting Shark

Since you have supplied the most part of the code ... you might like to see this little further 'edit' that might help you to continue ...

Edit: use a C++ 11 or greater compiler

// CStack.h //


#include <iostream>
#include <string>
#include <stdexcept>

// using namespace std;

class cInvalidStack : public std::exception
{
protected:
    std::string msg;
public:
    cInvalidStack( const std::string& msg = "" ) : msg(msg) {}
    virtual std::string& what() = 0;
} ;



class cInvalidPush : public cInvalidStack //exception if stack is full
{
public:
    cInvalidPush() : cInvalidStack( "Stack is full." ) {}
    std::string& what() { return msg; }

} ; //end class

class cInvalidPop: public cInvalidStack //exception if stack is empty
{
public:
    cInvalidPop():cInvalidStack( "Stack is empty." ) {}
    std::string& what() { return msg; }

} ; //end class




class CStack // holds the prototype of functions //
{
private:
    int* ptr_stk; //points to an array of integer
    int top; //contains the index value of array from where the value will be pushed and poped
    int max_size;
public:
    CStack (const int stackSize = 10 ); //default size for the stack is 10
    ~CStack();

    void push( const int ); //push the value in array of integers pointed by int *ptr_stk
    int pop();  //pop the value array of integers pointed by int *ptr_stk from the top of stack

    int isFull() const; //returns 1 if stack is empty otherwise 0
    int isEmpty() const; //returns 1 if stack is full otherwise 0
    int size() const { return top; } // …
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

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

@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

Addendum:

The comments at the top of the function below ...
are hopefully obviously seen to be wrong.

I simply forgot to change the comments (delete the comments) when I changed the code ...
from returning a void ... and passing in a ref...
to passing in a const value and returning the updated size.

// returns new size by ref... //
int takeInAndWrite( fstream& fs, const int siz )
{
    Student stud;
    int count = siz;
    while( true )
    {
    // ...

Also, I was thinking about the problem called the 'endian problem' ...

http://en.wikipedia.org/wiki/Endianness

A way to handle that problem could be to change both the integers in the struct to fixed length C strings if reading in number data as numbers ...and then converting them to strings to be stored in the struct

Then reverse the proccess after reading the struct back from file.

David W 131 Practically a Posting Shark

Ah ha ...

@ArpitJ.25

you have arrived at a wonderful spot to hang out to see all the code examples sailing past you ...

Now ... if you try out the easy examples ... see if you can make some changes and fixes ...

Note all the compiler error messages and how to fix them ...

You will soon enough be sailing too :)

David W 131 Practically a Posting Shark

You could try something like this ... to get you started:

// binFile_structStudent.cpp //


// This example allows ONLY UNIQUE student ID's //

#include <iostream>
#include <fstream>
#include <cstring> // re. strcpy
#include <climits> // re. INT_MAX, INT_MIN


using namespace std;


// NOTE! file gets created first time program is run //
const char* FNAME = "stud.bin";

const int MIN_ID = 1000;
const int MAX_ID = 9999;
const int MIN_MARK = 0;
const int MAX_MARK = 100;
const int TOT_NAME_CHARS = 20;



struct Student
{
    int id;
    char name[TOT_NAME_CHARS];
    int mark;

    // ctors ... //
    Student() : id(-1), mark(-1) { strcpy( name, "unknown"); }
    Student( int i, const char* n, int m ) : id(i), mark(m) { strcpy( name, n); }

    fstream& save( fstream& fs ) const
    {
        fs.write( (char*)this, sizeof(Student) );
        return fs;
    }
    fstream& load( fstream& fs )
    {
        fs.read( (char*)this, sizeof(Student) );
        return fs;
    }

    void print() const
    {
        cout << id << ' ' << name << ' ' << mark;
    }
} ;



////////////////////////////////////////////////////////////
// BEGIN 5 UTILITIES helpful to students here //////////////
int takeInInt( const char* msg, int min = INT_MIN, int max = INT_MAX )
{
    int val = 0;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
        {
            if( val >= min && val <= max )
            break;
            cout << "Valid input range here is: "
                 << min << ".." << max << endl;
        }
        else
        {
            cout << "Valid integers …
David W 131 Practically a Posting Shark

Late comment to add:

(It is too late now to edit the above code.)

// It might be better to just use a double for the total ? //
// Be aware of the potential problem in the result when you divide
// an integer value by an other integer value !!! //

David W 131 Practically a Posting Shark

Late comment to add:

(It is too late now to edit the above code.)

// It might be better to just a double for the total ? //
// Be aware of the potential problem in the result when you divide
// an integer value by an other integer value !!! //

David W 131 Practically a Posting Shark

You may fine this little edit/clean_up of your code ... a useful example for your future coding problems ...

Note: little typos in your code will cause your code to NOT compile.

For example:

for (moneky = 0, monkey ...
What is the typo above?

// monkey_food.cpp //


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

using namespace std;


const int MONKEY_TOT = 3; // number of monkeys
const int NUM_DAYS = 2;   // KEEP small for testing, change later //


void takeInFoodEaten( double food[MONKEY_TOT][NUM_DAYS] );
void dispFoodEaten( double food[MONKEY_TOT][NUM_DAYS] );




int main ()
{
    double food[MONKEY_TOT][NUM_DAYS]; // array to store information

    // You are NOT using these !!! //
    /*
    int monkeys;
    int days;
    int most = 0;
    int least = 0;
    int total = 0;
    double average = 0;
    */

    takeInFoodEaten(food);

    // rest of program done here //
    dispFoodEaten(food);

    return 0;
}





void takeInFoodEaten(double food[MONKEY_TOT][NUM_DAYS])
{// Fill array with numbers
    for( int monkey = 0; monkey < MONKEY_TOT; monkey++ )
    {
        for( int day = 0; day < NUM_DAYS; day++ )
        {
            cout << "Enter pounds of food eaten by monkey "
                 << (monkey + 1) << ", day " << (day + 1) << ": ";
            cin >> food[monkey][day];
            cout << "You entered : " << food[monkey][day] << endl;
        }
        cout << endl;
    }
}


void dispFoodEaten( double food[MONKEY_TOT][NUM_DAYS] )
{// Sum all food eaten (array elements) by all monkeys

    int total = 0, monkeyDayMealCount = 0;
    double average = 0;

    for( int monkeys = …
David W 131 Practically a Posting Shark

No problem ... :)

There are many ways ...

Sometimes ... simple is easier to see for students.

But yes, I prefer using a format string in many contexts.