David W 131 Practically a Posting Shark

You may like to file your data using commas to delimit the data record fields.

That way you can easily handle missing fields:

MovieName1,Genre1,HeroOfMovie1,HeroineOfMovie1
MovieName2,Genre2,,HeroineOfMovie2
MovieName3,Genre3,HeroOfMovie3,

And display as:

MovieName1::::Genre1::::HeroOfMovie1::::HeroineOfMovie1
MovieName2::::Genre2::::NA_HERO::::HeroineOfMovie2
MovieName3::::Genre3::::HeroOfMovie3::::NA_HEROINE

This example of sorting data records and finding data records using the C++ library functions may help you to get started.

This example uses an array of Student records. It demo's the idea of sorting on various fields and finding records that have particular field values.

// sortStudentsById_with_find2.cpp //

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

#include <algorithm> // re array sort, find, etc...
#include <vector>

using namespace std;

const int SIZE_STUDENT_ARY = 5;

class Student
{
public:
    // ctors...
    Student() : age(0), grade(0), id(0) {}
    Student( int age, int grade, int id, const string& name )
    : age(age), grade(grade), id(id), name(name) {}

    void setAge( int age ) { this->age = age; }
    void setGrade( int grade ) { this->grade = grade; }
    void setId( int id ) { this->id = id ; }
    void setName( const string& name ) { this->name = name ; }

    int getAge() const  { return age; }
    int getGrade() const { return grade; }
    int getId() const { return id; }
    string getName() const { return name; }

    void print( ostream& os ) const
    {
        os << left << setw(14) << name << ' '
           << setw(7) << id << ' '
           << setw(7) << grade << ' '
           << age << …
David W 131 Practically a Posting Shark

Ok ... you have multiple potential problems.

It is often best to solve them one at a time.

A 1st problem is your driver test program.

So here, I just use the STL list to show a ...
'proof of concept' ... working test program.

Once you have all the bugs out there ...

then with a well tested list ...
(i.e. after all aspects of that list are tested, except for the 'glue' part)

then attack the problem of your 'glue' function that joins two lists of your own home grown design.

Here is an example of a 'proof of concept' test program that uses the well tested STL list:

// glueTwoLists.cpp //

//  Program that takes two linked list objects and
// 'glues' second' list to end of first ...

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

using namespace std;

// some utilities used here ...

string takeInString( const string& msg = "" )
{
    cout << msg << flush;
    string val;
    getline( cin, val );
    return val;
}
char takeInChr( const std::string& msg = "" )
{
    string reply = takeInString( msg );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChr( "More (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}
int takeInValidInt( const string& msg )
{
    int val;
    while( true )
    {
        cout << msg << flush;
        if( cin >> val && cin.get() == '\n' )
            break;
        else …
David W 131 Practically a Posting Shark

As well advised by Dani's @Moschops above ...

you can streamline your code and logic flow by using the STL 'set' container ...

If you want to preserve the original order of the elements,
that could also be handled using sets by using something like this ...

// eraseDuplicateStoredStrings.cpp //


/**
    I'm making a word unscrambler, an anagram solver of sorts.
    So, I've stored all possible variations of the word instoredstrings
    which is an array of strings.
    Now, i need to delete all the same strings in storedstrings
    and then store the unique strings in another array of strings ...
**/

#include <iostream>
#include <string>
#include <vector>
#include <set>


using namespace std;

class MyStrings
{
public:
    // default ctor...
    MyStrings() {}
    // ctor from array ...
    MyStrings( const string ary[], size_t size ) ;

    void del_duplicates();

private:
    vector< string > storedstrings;
    friend ostream& operator << ( ostream& os, const MyStrings& ms );
} ;


// friend def'n ...
ostream& operator << ( ostream& os, const MyStrings& ms )
{
    vector< string >::const_iterator it;
    for( it = ms.storedstrings.begin();
         it != ms.storedstrings.end();
         ++ it )
    {
        os << *it << ' ';
    }
    return os;
}

// ctor def'n ...
MyStrings::MyStrings( const string ary[], size_t size )
{
    vector< string > tmp( ary, ary+size );
    storedstrings.swap( tmp );
}

void MyStrings::del_duplicates()
{
    // 1st step ... rid duplicates by getting (unique) 'set version'
    set< string > tmpSet;
    vector< string >::const_iterator cv_it;
    for( cv_it = storedstrings.begin(); cv_it != storedstrings.end(); ++ cv_it …
David W 131 Practically a Posting Shark

This demo of a menu -> choice pattern is simple and easily adapted to many student type menu -> choice type problems.

Note how it simply avoids the very common ...

beginning student problem

of 'dangling char's left in the cin stream' :

// showMenuTakeInChoice.cpp //

#include <iostream>
#include <string>


const std::string MENU =
    "1. Save a new password\n"
    "2. Display all passwords\n"
    "3. Exit\n\n"
    "Choose 1, 2, or 3: ";

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

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


int main()
{
    char choice;
    bool quit = false;
    while( !quit )
    {
        switch( (choice = takeInChr( MENU )) )
        {
            case '1':
                std::cout << "\n'1' is under construction"
                          << " ...\n\n";
            break;
            case '2':
                std::cout << "\n'2' is under construction "
                          << " ...\n\n";
            break;
            case '3':
                quit = true;
                takeInChr( "\nPress 'Enter' to "
                           "continue/EXIT ..." );
            break;
            default:
                std::cout << "\n'" << choice
                          << "' is NOT a valid choice "
                          << "here ...\n\n";
        }
    }
}
David W 131 Practically a Posting Shark

This demo of a menu -> choice pattern is simple and easily adapted to many student type menu -> choice problems.

Note how it simply avoids the very common ...

beginning student problem

of 'dangling char's left in the cin stream' :

// showMenuTakeInChoice.cpp //

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


const std::string MENU =
    "1. Save a new password\n"
    "2. Display all passwords\n"
    "3. Exit\n\n"
    "Choose 1, 2, or 3: ";

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

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


int main()
{
    char choice;
    bool quit = false;
    while( !quit )
    {
        switch( (choice = takeInChr( MENU )) )
        {
            case '1':
                std::cout << "\n'1' is under construction"
                          << " ...\n\n";
            break;
            case '2':
                std::cout << "\n'2' is under construction "
                          << " ...\n\n";
            break;
            case '3':
                quit = true;
                takeInChr( "\nPress 'Enter' to "
                           "continue/EXIT ..." );
            break;
            default:
                std::cout << "\n'" << choice
                          << "' is NOT a valid choice "
                          << "here ...\n\n";
        }
    }
}
David W 131 Practically a Posting Shark

Further to comment by @vegaseat ...

you can print out ...

print( type( in_file ) ) # debugging Python object types #
print( type( indata ) )

You may like to see this Python 3 revision ...
(that uses Python exceptions to handle the 'abort' option)

# copyFileToFile.py #

from os.path import exists
import os

##from sys import argv
##script, fnameIn, fnameOut = argv

fnameIn, fnameOut = 'myData.txt', 'myDataCopy.txt'

class AbortCopyException( Exception ):
    pass

try:
    with open( fnameIn ) as fin:
        #print( type(fin) )
        inData = fin.read()
        #print( type(inData) )
        print( "There are {} bytes of data in file {} to copy.".
               format( len(inData), fnameIn ) )

        if exists( fnameOut ):
            while( True ):
                ans = input( "\nPress 'Return' to continue and to "
                             "OVERWRITE \nexisting output file: '{}'"
                             "\nOR ... \nPress 'a' to abort ?  ".
                             format( fnameOut ) ) #argv[2]
                if ans in '\n':
                    break
                if ans.lower() == 'a':
                    raise AbortCopyException()
                print( "\nMust enter 'a' or press 'Enter' ..." )

        try:
            with open( fnameOut, 'w' ) as fout:
                print( "\nCopying file '{}' to file '{}' ...".
                       format( fnameIn, fnameOut ) )
                fout.write( fin.read() )
            print( "Copying now done." )

        except:
            print( "There was a problem opening or reading file {}".
                   format( fnameOut ) )
except( AbortCopyException ):
    print( "Aborting copy ... " )
except:
    print( "There was a problem opening or writing file {}".
           format( fnameIn ) )


input( "\nPress 'Enter' to continue/EXIT ... " )
David W 131 Practically a Posting Shark

Actually ... the notion of 'between' ...

could actually be expressed as this:

class MyTime: # 24 hour clock #

    def __init__(self, hrs=0, mins=0, secs=0):
        self.hours = hrs
        self.minutes = mins
        self.seconds = secs
        # normalize ... #
        if self.seconds >= 60:
            self.minutes += self.seconds//60
            self.seconds = self.seconds % 60
        if self.minutes >= 60:
            self.hours += self.minutes//60
            self.minutes = self.minutes % 60
        if self.hours >= 24:
            self.hours = self.hours % 24

    def get_sec(self):
        return (self.hours*60 + self.minutes) * 60 + self.seconds

    def __str__(self):
        return '{:02d}:{:02d}:{:02d}'.\
               format( self.hours, self.minutes, self.seconds )

    def between(self, t1, t2 ):
        return t1.get_sec() <= self.get_sec() <= t2.get_sec() \
               or t2.get_sec() <= self.get_sec() <= t1.get_sec()
David W 131 Practically a Posting Shark

@shyamdadhich

Please start a new thread for your question.

Best to ask C programming questions in the C forum.

David W 131 Practically a Posting Shark

Yes ... it is.

These are the program output results I get:
(# Note: comment added #)

t1 = 09:59:59
t2 = 10:00:01
t = 10:00:00
between( t2, t, t1 ) = False
between( t1, t, t2 ) = True # NOTE: True as expected #
between( t, t1, t2 ) = False
between( t, t, t ) = True

David W 131 Practically a Posting Shark

You will need to provide more information about your program ... for example ... provide a complete working program that illustrates your question/problem?

Note:

storedstrings[i][k]
and

storedstrings[i]

are NOT the same thing !

But without your code that defines 'storedstrings' ... we can not really say much more.

David W 131 Practically a Posting Shark

Well ... there are many ways to go about your problem.

If you have no particular design constraints or requirements (beyond those listed below) ...

this next little demo may give you some more ideas:

// inventoryBagSystem.cpp //

/*
    I have inventory system which works with item-bags.
    There are 4 different item-bags, sizes: 4, 8, 12 and 16

    ...

    Now my big problem is how to check if one of those
    inventory (slots) have (a) free place?
*/

#include <iostream>
#include <iomanip> // re. setw
#include <sstream> // re. stingstream obj's
#include <string>
#include <vector>

#include <algorithm> // re. vector find ...

using namespace std;

const string HEADER =
    "This demo will ask for a (next) bag name ...\n"
    "and then asks for that bag size.\n"
    "Then, asks for the name of an item "
    "to put in a slot in that bag,\n"
    "until done for that bag, or that bag is filled.\n"
    "Then, will loop for next bag name and size "
    "... until 'done'.";


class Bag
{
public:
    Bag() {}
    Bag( const string& name="", size_t n=16 ) : name(name), max_len(n)
    {
        slots.reserve(max_len);
    }
    size_t size() const { return slots.size(); }
    size_t max_size() const { return max_len; }
    bool is_filled() const { return (max_len == slots.size()); }

    void set_name( const string& name )
    {
        this->name = name;
    }

    string get_name() const { return name; }

    bool add_item()
    {
        if( !is_filled() )
        {
            cout << "Item to add: " << flush;
            string item;
            getline( cin, item );
            slots.push_back( item …
David W 131 Practically a Posting Shark

Another way ...

struct Bag
{
    string name;
    vector< string > slots;

    Bag() {}
    Bag( const string& name, size_t n )
        : name(name)
    {
        slots.reserve(n); // or maybe resize(n) ? //
    }
} ;

// ...

vector < Bag > store;
David W 131 Practically a Posting Shark

What is wrong with this code?

char* processIt( /*  */ )
{
    char local_buf[90];
    /* get some stuff into local_buf */
    return loacal_buf; /* Hint! Is this line ok? */
}
David W 131 Practically a Posting Shark

You might try something like this ...

# compareTimes.py #

class MyTime: # 24 hour clock #

    def __init__(self, hrs=0, mins=0, secs=0):
        self.hours = hrs
        self.minutes = mins
        self.seconds = secs
        # normalize ... #
        if self.seconds >= 60:
            self.minutes += self.seconds//60
            self.seconds = self.seconds % 60
        if self.minutes >= 60:
            self.hours += self.minutes//60
            self.minutes = self.minutes % 60
        if self.hours >= 24:
            self.hours = self.hours % 24

    def get_sec(self):
        return (self.hours*60 + self.minutes) * 60 + self.seconds

    def __str__(self):
        return '{:02d}:{:02d}:{:02d}'.\
               format( self.hours, self.minutes, self.seconds )


def between( t1, t, t2 ):
    return t1.get_sec() <= t.get_sec() <= t2.get_sec()


t1 = MyTime( 9, 59, 59 )
print( 't1 =', t1 )

t2 = MyTime( 10, 0, 1 )
print( 't2 =', t2 )

t = MyTime( 10, 0, 0 )
print( 't =', t )

print( 'between( t2, t, t1 ) =', between( t2, t, t1 ) )
print( 'between( t1, t, t2 ) =', between( t1, t, t2 ) )
print( 'between( t, t1, t2 ) =', between( t, t1, t2 ) )

print( 'between( t, t, t ) =', between( t, t, t ) )
David W 131 Practically a Posting Shark

This may give you some ideas to get you started ...

# fileTypes.py #

myFiles = [ 'news.txt', 'data.dat', 'programcpp.cpp', 'programc.c' ]

myTypes = [ '.txt', '.dat', '.cpp', '.c' ]


for name in myFiles:
    found = False
    for typ in myTypes:
        if typ in name:
            found = True;
            break;
    if found:
        i = name.find( typ )
        print( i, name[:i], typ )
David W 131 Practically a Posting Shark

If you sort the array of strings ...

you can then traverse the sorted array

and skip over all duplicates

David W 131 Practically a Posting Shark

re. the other part of your question ...

the use of typedef can either be

helpful to your code flow

or

hinder (hide from) your understanding

what the code is doing

For an example of common use:
One can easily make iterators to arrays using typedef

For an example of questionable/controversial use:
some hiding of pointers with typedef

There ... now you can:

Google typedef hiding pointer problem

and see here:

http://discuss.fogcreek.com/joelonsoftware1/default.asp?cmd=show&ixPost=10506

David W 131 Practically a Posting Shark

Really ... one does need more info and the particulars of your inventory data management problem ?

David W 131 Practically a Posting Shark

One way (off the top) could be ...

struct Bag4
{
    bool filled;
    string items[4];

    Bag4() : filled(false) {}    
} ;

// etc ...
David W 131 Practically a Posting Shark

@R_R_A please note: the above post was not meant to in anyway discourage you from studying the very useful code example by @tinstaafl

You will do well to study his skillfully designed code examples regularly provided here ... at our Dani's wonderful coding forum :)

'Quick Sort' is a method that you will want to know if you go beyond just the 'beginnings' ... or if you need to sort data sets of more than just a few elements, (unless those data sets are already sorted, i.e. all sorted, except for maybe an element or two.)

Also handling 2D arrays (or multi-D arrays) is a skill to acquire if you wish to go beyond the 'beginnings' ...

Anyways, take a look at the added comments here ...

and the code // commented out

and the edits / changes ...

These may make that example code simpler to run
and for you to follow ...

You can run this from the command line or a batch file as per the following batch file example:

@echo off

rem fileName: run_2dExample.bat

2dExample input2.txt
pause

Ok ... take a look at this code again, if you like ...

// 2dExample.cpp //  // this version: 2014-07-02 //

// revised from C++ code posted 2014-07-01 at ...
// http://www.daniweb.com/software-development/cpp/threads/480984/write-a-program-that-reads-in-a-set-of-positive-integers-representing-test
// Original code by DANI'S 'tinstaafl' expert coder ... //



#include <iostream>
#include <fstream>

#include <cstring> // re. memcpy

using namespace std;

const int MAX_SIZE = 100;
const int LAST_ELEMENT = …
David W 131 Practically a Posting Shark

Actually ... I like this for 'simple student type validation' of keyboard user input of integers ...

int takeInValidInt( const char prompt[] )
{
    for( ; ; ) /* an example of a C/C++ forever loop ... until 'return' */
    {
        int numGood, extraChars, testInt;
        printf( prompt ); fflush( stdout );
        numGood = scanf( "%d", &testInt );
        extraChars = ( getchar() != '\n' );

        if( numGood == 1 && !extraChars ) return testInt;

        if( !numGood )
            puts( "Invalid input! Integers only please ..." );
        else if( extraChars )
            puts( "NO extra char's permitted at end." );

        while( getchar() != '\n' ); /* 'flush' stdin ... as we go ... */
    }
}
David W 131 Practically a Posting Shark

You can read the returned value when using scanf or fscanf, to see if an appropriate value was 'scanned in':

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

int getValidInt( const char prompt[] )
{
    for( ; ; ) /* an example of a C/C++ forever loop ... until 'return' */
    {
        int numGood, testInt;
        fputs( prompt, stdout ); fflush( stdout );
        numGood = fscanf( stdin, "%d", &testInt );
        while( getchar() != '\n' ); /* 'flush' stdin ... as we go ... */
        if( numGood == 1 ) return testInt;
        /*else ...*/
        puts( "Invalid input! Integers only please ..." );
    }
}

Or ...

/* takeInValidInt.c  */ /* 2013-05-29 */

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

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

int takeInValidInt( const char prompt[] )
{
    for( ; ; ) /* an example of a C/C++ forever loop ... until 'return' */
    {
        int numGood, testInt;
        printf( prompt ); fflush( stdout );
        numGood = scanf( "%d", &testInt );

        if( getchar() == '\n' )
        {
            if( numGood == 1 ) return testInt;
            /*else ...*/
            puts( "Invalid input! Integers only please ..." );
        }
        else 
            puts( "Integers only please ... NO extra char's permitted at end." );

        while( getchar() != '\n' ); /* 'flush' stdin ... as we go ... */
    }
}

char takeInChar( const char* msg )
{
    char chr;
    printf( msg ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' ) while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}


int more() /* defaults …
David W 131 Practically a Posting Shark

The OP wanted to be able to print out the original scores that were in the file ... so these would need to be printed out as they were read from file in the above example by "tinstaafl"

Quick sort is an appropriately fast sort for large arrays, but often is 'over-kill' for small ... especially for beginner coders.

Rather than use a 2-D array (added complexity?)... using a 1-D array of struct ... may be simpler to understand and code for beginner coders?

struct ScoresFreq
{
   int score;
   int freq; // frequency of score

   ScoresFreq() : score(0), freq(0) {}
} ;

But if the scores are all in the range of 0..100

just using an array of 101 int's ...

all initaled to 0

may be the simplest beginner approach?

Just update the array for each score read from file:
(while also printing out that score)

++ array[score] ; // score is in range 0..100 //

Then ... just print out the array ...
skipping over the 'zero entries'
to get a printout of scores and frequencies
in order of increasing score value

David W 131 Practically a Posting Shark

Take a look at this revision that uses a (data) struct to simplify and help organize the flow of the data processing:

/*
    Write a function, CountElement, that receives two arguments:
    * a 2-dimensional char array
    * and the size of the array.
    This function counts
        1. the number of digits,
        2. small letters,
        3. capital letters and
        4. symbols in the char array,
    and returns the counts.

    Write a driver function to test your function and
    print your results
        to the computer screen
        and to a text file.

    Note: in this example, both of the above two
    functions are combined into just one function.

*/

#include <iostream>
#include <iomanip>
#include <fstream>
#include <cctype> // re. isalpha, islower, etc...

using namespace std;

// constant char array size (of each row) //
const int SIZE2 = 6;

const char* FNAME = "outputResult.txt";

struct MyData
{
    int numLowerCase;
    int numUpperCase;
    int numDigits;
    int numOther;

    MyData() : numLowerCase(0), numUpperCase(0),
               numDigits(0), numOther(0) {}
} ;


// header of void function to analyse, show and file the array //
void calShowAndFile( const char ary[][SIZE2], int size );



int main()
{
    // initial/get a demo test array ... //
    const char ary[][SIZE2] =
    {
        { 'y', '7', '9', '0', 'K', '!' },
        { 'A', ',', '1', 'o', 'U', 'P' },
        { 'W', 'g', '6', '2', '%', '$' },
        { '*', 'h', 'J', '#', '@', 'i' }
    };

    int size = sizeof ary / sizeof *ary; // number of rows //

    calShowAndFile( ary, size );

    //system …
David W 131 Practically a Posting Shark

This example may be closer to what would be expected of just a 'beginning student:

1 -> NO STL used
2 -> Simple bubble sort used
3 -> Only tricky part ... counting / outputing ALL repeats

// scores_counts.cpp //

/*
    Write a program that reads in a set of positive integers,
    representing test scores for a class, and outputs how
    many times a particular number appears in the list.
    You may assume that the data set has, at most, 100
    numbers and that -999 marks the end of the input data.

    The numbers must be output in increasing order.

    For example, with this input data in file 'input2.txt':
    55 80 78 92 95 55 78 53 92 65 78 95 85 92 85 95 95 -999

    the output is:

    File 'input2.txt' holds these 17 scores:
    55 80 78 92 95 55 78 53 92 65 78 95 85 92 85 95 95

    Or ... showing scores sorted in ascending order:
    53 55 55 65 78 78 78 80 85 85 92 92 92 95 95 95 95

    SCORE      FREQUENCY
    53         1
    55         2
    65         1
    78         3
    80         1
    85         2
    92         3
    95         4

    For bonus ... display a bar-graph of the distribution ...

*/

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

using namespace std;

const string FNAME = "input2.txt";
const int MAX_ARY_SIZE = 100;


int loadAryFromFile( int ary[], int max_size, const string& filename );
void print( const int ary[], int size );
void …
David W 131 Practically a Posting Shark

In any case you will want to see this:

http://www.cplusplus.com/reference/cctype/

remember to:
#include <cctype>

David W 131 Practically a Posting Shark

Not sure what you are trying to do ?

function counts the number of digits, small letters, capital letters and symbols in the char array, and returns the counts

Are you to read a text file into an array of words?

Or ... to read the whole file into one big char array?

Or ... are you just given some array of char to start?
(or an array of arrays of char ... perhaps a 'ragged array' ?)

David W 131 Practically a Posting Shark

I really can not tell without seeing your exact code and having the exact same testing setup.

But ... C++ code that is well written ... to accord to standard C++ ... will (normally) compile ok and run ok on any other C++ standard complient system.

David W 131 Practically a Posting Shark

But ... better to use C++ string and getline for input of names.

Also ... you will want to validate / handle bad (numeric) input (especially - so your program will not crash.)

Also ... you will want an array (or some other C++ container like a vector) to hold your 'Student' objects ...

This example may get you started ...

// classStudent_test.cpp //

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

using namespace std;

const int MAX_NUM_STUDENTS = 3; // keep small while testing //

class Student
{
private:
    int semester, rollno;
    string name;

public:
    void input_semester()
    {
        cout << "Enter student's semester: ";
        while( !( cin >> semester ) || cin.get() != '\n'
               || semester <= 0 || semester > 4 )
        {
            cin.clear();
            cin.sync();
            cout << "\nOnly integers in range 1..4 accepted here ...\n";
            cout << "Enter student's semester: ";
        }
        cin.sync();
    }
    void input_rollno()
    {
        cout << "Enter student's roll_no: ";
        while( !( cin >> rollno ) || cin.get() != '\n'
               || rollno <= 0 )
        {
            cin.clear(); // clear all error flags
            cin.sync(); // 'flush' din stream ...
            cout << "\nOnly valid positive integers accepted here ...\n";
            cout << "Enter student's roll_no: ";
        }
    }
    void input_name()
    {
        cout << "Enter student's name (last, first): ";
        getline( cin, name );
    }

    void display() const // definition of member function to display values
    {
        cout << "Semester: " << semester
             << ", Rollno: " << setfill( '0' ) << setw(4) << rollno
             << ", …
David W 131 Practically a Posting Shark

Your code above will NOT compile error free.

See the '1st round' of corrections suggested ...
(see changes and added comments)

//#include<iostream.h>

#include <iostream>

// need to add
using namespace std;

class id
{
private:
    //char *name;                      // declaration of private data members of class
    char name[80]; // need to resevere memory to hold this
    int rollno, semester ;

public:
    void get_name(/* char *name*/ )           // definition of member functions of class
    {
        cout<<"enter your name: ";
        //cin>>name;    //
        cin.getline( name, sizeof(name) );
    }

    void get_rollno(/* int rollno*/ )
    {
        cout<<"enter your rollno: ";

        cin>>rollno; // but will crash on non int input

        // NEED to add (at least) something like this ...
        cin.sync(); // 'flush' cin stream ...
    }
    void get_semester(/* int semester*/ )
    {
        cout<<"enter your semester ";
        cin>>semester; // but will crash on non int input //

        // NEED to add (at least) something like this ...
        cin.sync(); // 'flush' cin stream ...
        cout<<endl;
    }
    void display( )                     // definition of member function to display values
    {
        cout << "name of student: " << name;
        cout << ", rollno of student: " << rollno;
        cout << ", semester of student: " << semester;
    }


};           

//main()                            // main body
int main()
{ 

    //int  rollno, semester; // NOT USED //
    //char *name;

    id obj1;

    for( int i=0;i<2;i++)              // using for loop to get data of 2 students
    {
        //obj1.get_name(name);                       // calling member functions of objects
        //obj1.get_rollno(rollno);
        //obj1.get_semester(semester);
        obj1.get_name();                       // calling member functions of objects
        obj1.get_rollno();
        obj1.get_semester(); …
David W 131 Practically a Posting Shark

Also note:

if number is divisible by 10 ... it is ALSO divisable by 5 and 2 ... and it will end with (at least) one 0

if number is divisible by 5, it ends in 5 or 0
if it ends in 0, it is also divisible by 2 and 10 (if >=10)

if a number is divisable by 2 ... it will end in 0, 2, 4, 6 or 8 ... and will NOT be divisible by 5 or 10 UNLESS it ends in 0 ( and >= 10 )

so could test and report like this:

int flags[3] = {0}; /* get memory and initial all to 0 */

if( num % 2 == 0 ) flags[0] = 1;
if( num % 5 == 0 ) flags[1] = 1;
if( flags[0] && flags[1] ) flags[2] = 1; /* num%10==0 */

/* now can interpret and report flags */

David W 131 Practically a Posting Shark

What is this:

using namespace std;

struct karmand{
    char nam[10];
    char shomare[10];
    char sx[10];
    char mm[10];
    char rgh[10];
    }list[s]; /*  s = ??? */

Don't you mean to code:

struct Contact
{
    // your contact info gets saved here
} ;

const int MAX_SIZE = 100;

Contact MyContacts[MAX_SIZE];

Your code seems to be C code (except for the 'using namespace std;' line ... maybe best to re-post as all C code in the C forum?

Also, do not use conio (cls, getch, etc) if you want portable code.

Best to always avoid dangerous use of gets.

In C++ use getline and a C++ string ...

In C use fgets
( or my fixedFgets
or my C emulation of C++ getline, called readLine )
(free for asking)

Also ...

What does NOT work right?

(What is your code supposed to do?
vs
What does it presently do?)

Does it compile error free?
(If not, please supply error messages.)

David W 131 Practically a Posting Shark

You need to add ...

#include <cstdlib> // re. exit

but do not use exit ...

It's not really needed ...
Just return some none 0 error (flag) value, if you wish.

(The code already prints an error message if there was a file finding/opening problem.)

You do not need to code for the overloaded =
The default supplied here is just fine.

You do not need the code for:

/*
std::ostream& operator<<(std::ostream& op,const Choices& choice)
{
    //print the string corresponding to the value of enum type Choices
        op << SELECT[choice]; //print output
    return op;
}
*/

it is not used ... since the SELECT[i] string is NOW printed

When I compiled you code on my PC it compiled ok and seemed to run op ... (quick test only)

David W 131 Practically a Posting Shark

Ok ... here is a 'debugging' problem / solution process to try :)

Take my code ...
compile
check

Then replace blocks/functions with 'comparable code'
from your program ...
compile and check ...
to find the code problem

David W 131 Practically a Posting Shark

Oops ... see/use the following instead (to take in a float)

(I had modified the code from a student example I gave years ago ... an example for integer 'take in' ... and missed changing a few comments (and things) re. the float version ...)

/*
    Prompt and loop until user takes in a valid float.
    The float val input here is also checked and accepted
    iff in  range >= min
*/
float takeInFltMin( const char* msg, float min )
{
    float val = 0;
    int isGoodVal = 0;
    while( ! isGoodVal )
    {
        /* show prompt for input ...
           fflush( stdout) ensures prompt displayed right NOW
        */
        printf( msg ); fflush( stdout );

        /* Note logic below ...

           if scanf returns 1 below means ...
           ***there WAS ONE***
           good float data presented at first in input stream

           then ... if getchar() == '\n'
           ***that means that '\n' WAS the VERY NEXT CHAR***

           which means no space or other chars entered there
           (after float val) before a '\n' char was entered ...
           so ... ***WAS good float*** data presented
           i.e. no 'junk' was entered by user 'by accident'
           (after int data was entered and before '\n' pressed)
        */

        if( scanf( "%f", &val ) == 1 && getchar() == '\n' )
        {
            isGoodVal = 1; /* Ok ... so far, so good */
        }
        else
        {
            printf( "\nDecimal input only here please ...\n" );
            while( getchar() != '\n' ) ; /* flush stdin ... */
        }

        /* NOW check if …
David W 131 Practically a Posting Shark

you still did not offer a solution to my problem of initializing an object with no parameters (using the default values in the constructor).

Please note the changes to your erroroneous (ctor) code that were made here ...

HardwareRecord::HardwareRecord( int account, string name, string description, double price )
: myAccountNumber(account), myName(name), myDescription(description), myPrice(price)
{
    /* *** NO ***
    setAccountNumber(account);
    setName(name);
    setPrice(price);
    setDescription(description);
    */
}

What type of computer are you working on? If it's a mac, I can compress my project for you to check on your compiler.

I use Window 7 OS on ACER Laptop with Intel i5 CPU (64-bit OS)

Your code worked just fine, even when I uncommented the line

HardwareRecord temp;

When I just now made these code changes ...
all compiled and output was as expected ... ok.

// Can do this later ... //
void wipeRecords( /* fstream& theFile*/ )
{

    HardwareRecord temp; 
    cout << "\nInside wipeRecords default ctor called ok ... \n"; // prints ok when choice 0 called //
    /*
    temp.setPrice(10.52);
    cout << temp.getPrice() << endl;
    for (int i = 0; i < 100; i++)
    {
        //convert record from binary and assign to temp
        //make temp "wipe itself"
    }
*/

On mine, I get the error with No matching constructor
for initialization...

I thought you said (the code I sent) worked ok on (both) your compiler(s) ?

David W 131 Practically a Posting Shark

Did you not read, research ... and then understand the added comments?

I understand everything except for your usage of size_t, and the clearing of the cin error flags. What would happen with it if a person inputs a value less than 0?

Accepting only unsigned numbers eliminates the need to add exception code to reject negative values input ... since cin will flag as bad any neg values input and can handle by ...

if( cin >> val ) then
else ...

Once cin has error flags set ... until you clear them no more input will work ok.

Compiler error messages can sometimes be quite 'tricky' and then 'misleading'...

That is why I like to also develope in small incremental code steps ... always keeping a copy of the last 'working step' ...

This can help to locate the section of (most probably the new) code where the code error lies ...

Did you see that you were also missing a header file?

Did you try to compile the code I provided to see if all your compilers handled it ok or not?

Clean simple logic code is usually easier to debug :)

David W 131 Practically a Posting Shark

@L7Sqr I appreciate your concern ... the example I provided was an example of a 'real' use ... in a typical student type coding problem / solution. The example only used one case of 'inline' ... and this also illustrated the relative raity of its (possibly appropriate?) use ... so now you may be able to see more of the 'intent' ...

David W 131 Practically a Posting Shark

It appears

  • that you have an even number count in your lists of grades ...

and

  • you want the output to be formatted as a list of list pairs ... but with the name as the fist element in the outer list.

So ...

# nameGradePairsList.py #

grades = [ '4.5', '4.4', '3.9', '4.2', '3.8', '3.7' ]

grade_pair_lst = [ 'Sue Girl' ]
pair = []
for i, grd in enumerate(grades):
    if i % 2 == 0:
        pair.append( grd )
    else:
        pair.append( grd )
        grade_pair_lst.append( pair )
        pair = []

print( grade_pair_lst )
David W 131 Practically a Posting Shark

Some next steps:

  1. validate and 'crash proof' input

  2. loop for more input until no more input desired

  3. break up program into jobs using functions

This little demo revision of your code my give you some more ideas ...

/* cylinderAreaVol.c */

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

#define MY_PI 3.1415926536

/* forward function declarations / function prototypes */

/* pass in prompt and min val to accept */
float takeInFltMin( const char* msg, float min ) ;

void calAndShow( float, float ) ;

char takeInChar( const char* msg ) ;
int more() ;



int main()
{
    do
    {
        float radius, height;

        printf("\n========Total surface area and "
                   "volume of a cylinder========\n");

        radius = takeInFltMin( "\nThe base radius.......: ", 0 );
        height = takeInFltMin( "\nCylinder height.......: ", 0 );

        calAndShow( radius, height );
    }
    while( more() );

    return 0;
}



/* loop until user takes in a valid int ... after prompt(s) ...  */
/* int here is also checked and accepted iff in  range >= min */
float takeInFltMin( const char* msg, float min )
{
    float goodVal = 0, val = 0;

    while( !goodVal )
    {
        /* show prompt for input ...
           fflush( stdout) ensures prompt displayed right NOW
        */
        printf( msg ); fflush( stdout );

        /* Note logic below ...

           if scanf returns 1 below means ...
           ***there WAS ONE***
           good int data presented at first in input stream

           then ... if getchar() == '\n'
           ***that means that '\n' WAS the VERY NEXT CHAR***

           which …
David W 131 Practically a Posting Shark

You could say that a pointer variable holds addresses ... adresses for any kind of 'object' ... including the address of an other pointer variable ... and in that case, you then have a 'pointer to a pointer'.

One very common use of pointers is when you allocate dynamic memory ... The pointer then holds the address to the first byte in that newly allocated memory.

How were you wanting to use pointers?

Can you supply some example code?

David W 131 Practically a Posting Shark

I think you can really clean up your code still and simplify it lots ...

Take a look at this and see the added comments ...

file: HardwareRecord.h

// file: HardwareRecord.h //

#ifndef HARDWARE_RECORD_H
#define HARDWARE_RECORD_H

#include <iostream>

class HardwareRecord
{
public:
    //constructor
    HardwareRecord( int account =0, std::string name ="",
                       std::string description ="",
                       double price =0.0 );

    // default copy ctor... is ok here ...
    //HardwareRecord operator = ( const HardwareRecord& );

    // 'set' and 'get' functions
    void setAccountNumber(size_t);
    size_t getAccountNumber() const;

    void setName(std::string);
    std::string getName() const;

    void setPrice(double);
    double getPrice() const;

    void setDescription(std::string);
    std::string getDescription() const;

    void wipeRecord(); //set everything to blank

private:
    size_t myAccountNumber;
    std::string myName;
    std::string myDescription;
    double myPrice;
};

#endif

file HardwareRecord.cpp

//  file HardwareRecord.cpp

#include <stdexcept>      // std::invalid_argument

#include "HardwareRecord.h"
// #include <iostream> // included above

using std::string;
using std::invalid_argument;

/* default copy ctor... is ok here ...
HardwareRecord HardwareRecord::operator= ( const HardwareRecord& aRecord )
{
    myAccountNumber=aRecord.myAccountNumber;
    myName=aRecord.myName;
    myDescription=aRecord.myDescription;
    myPrice=aRecord.myPrice;

    return *this; //allow for cascaded overloading
}
*/

HardwareRecord::HardwareRecord( int account, string name,
                                string description,
                                double price )
    : myAccountNumber(account), myName(name),
    myDescription(description), myPrice(price)
{
    /* *** NO ***
    setAccountNumber(account);
    setName(name);
    setPrice(price);
    setDescription(description);
    */
}



void HardwareRecord::wipeRecord()
{
    setAccountNumber(0);
    setName("");
    setPrice(0);
    setDescription("");
}

void HardwareRecord::setAccountNumber(size_t num)
{
    /*
    if (num < 0)
    {
        throw invalid_argument("The account number is not in the valid range (greater or equal to 0)");
    }
    else
    {*/
        myAccountNumber = num;
    //}
}

size_t HardwareRecord::getAccountNumber() const
{
    return myAccountNumber;
}

void HardwareRecord::setName(string name)
{

   myName=name;

}

string HardwareRecord::getName() const
{ …
David W 131 Practically a Posting Shark

You may also like to see this:

http://www.parashift.com/c++-faq/inline-functions.html

Here is an example that you can see where 'inline' might be appropriately placed and used ...

file: nvector.h

// file: nvector.h //

#ifndef NVECTOR_H
#define NVECTOR_H

#include <iostream>
#include <vector>

class Nvector
{
private:
    std::vector < double > vec;
public:
    Nvector( size_t n=0 ) ;
    Nvector( const std::vector< double >& ) ;

    void resize( size_t n ) { vec.resize(n) ; } // inline //
    void reserve( size_t n ) { vec.reserve(n) ; }

    double& operator [] ( size_t i ) { return vec[i]; }
    const double& operator [] ( size_t i ) const { return vec[i]; }

    typedef std::vector< double >::iterator iterator;
    typedef std::vector< double >::const_iterator const_iterator;

    iterator begin() { return vec.begin(); }
    iterator end() { return vec.end(); }
    const_iterator begin() const { return vec.begin(); }
    const_iterator end() const { return vec.end(); }

    size_t size() const  { return vec.size(); } // inline //

    Nvector& reverse();

    Nvector& operator += ( const Nvector& ) ;
    Nvector operator + ( const Nvector& ) const ;

    Nvector operator - () const;

    Nvector& operator *= ( double scale ) ;
    Nvector operator * ( double scale ) const ;

    double operator * ( const Nvector& ) const ;

    bool operator == ( const Nvector& ) const ;

    void print( std::ostream& ) const ;
} ;

inline
Nvector operator * ( double scale, const Nvector& nv )
{
    return nv * scale;
}

std::ostream& operator << ( std::ostream& os, const Nvector& nv );

#endif …
David W 131 Practically a Posting Shark

Or ... a very simple way to start could be like this ...
(that lets readily you use all the STL vector member functions)

// schools.cpp //

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

using namespace std;


struct Student
{
    string lname, fname;
} ;


ostream& operator << ( ostream& os, const Student& st )
{
    return os << st.lname << ", " << st.fname;
}


int main()
{
    // 'construct' school vs to have 3 floors
    vector < vector < vector < Student > > > vs ( 3 );

    // make each floor to have 5 classes
    for( int i = 0; i < 3; ++ i )
        vs[i].resize(5);

    // reserve room in each class for 20 students
    for( int i = 0; i < 3; ++ i )
    {
        for( int j = 0; j < 5; ++ j )
        vs[i][j].reserve(20);
    }

    // assign peter pan to floor 2, room3, seat 1
    Student tmp;
    tmp.lname = "Pan", tmp.fname = "Peter";
    vs[1][2].push_back(tmp);

    Student add[] =
    {
        {"Mary", "Jane"},
        {"Billy", "Bob"},
        {"Peggey", "Sue"}
    };

    int size = sizeof add / sizeof(Student);

    cout << "There are " << size << " students being added ...\n";

    for( int i = 0; i < size; ++ i )
         vs[1][2].push_back( add[i] );

    // show class vs[1][2] ...
    cout << "Class now has ... \n";
    for( size_t i = 0; i < vs[1][2].size(); ++i )
         cout << vs[1][2][i] << endl;
}
David W 131 Practically a Posting Shark

After you have the above working ... see added code and better comments here ... (but note the simpler and more symetric code demo'd above ... the 2nd example)

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

using namespace std;


void mergeFiles( ifstream& fin1, ifstream& fin2, ofstream& fout );

void showFile( const char* fname );


int main()
{
    ifstream fin1( "input1.txt" );
    ifstream fin2( "input2.txt" );
    ofstream fout( "output.txt" );

    mergeFiles( fin1, fin2, fout );

    fout.close(); // ensure flushed ... //

    showFile( "input1.txt" );
    showFile( "input2.txt" );
    showFile( "output.txt" );

    cout << "\nPress 'Enter' to continue/exit ... " << flush;
    cin.get();
    return 0;
}


void mergeFiles( ifstream& fin1, ifstream& fin2, ofstream& fout )
{
    int i1, i2, countIn = 0, countOut = 0;
    if( fin1 >> i1 ) ++ countIn;

    // Can firstly handle case of ...  if empty file 1 //
    if( fin1 ) // i.e. count == 1
    {
        // Then can handle case of ... if empty file 2 //
        if( fin2 >> i2 )
        {
            ++ countIn;
            while( fin1 && fin2 )
            {
                if( i1 <= i2 )
                {
                    fout << i1 << ' ';
                    ++countOut;
                    if( !(fin1 >> i1) )
                    {
                        fout << i2 << ' ';
                        ++countOut;
                        //break; // handled by while ... above //
                    }
                    else ++countIn;
                }
                else
                {
                    fout << i2 << ' ';
                    ++countOut;
                    if( !(fin2 >> i2) )
                    {
                        fout << i1 << ' ';
                        ++countOut;
                        //break; // handled by while ... above //
                    }
                    else ++countIn; …
David W 131 Practically a Posting Shark

try this fix:

// mergeFiles( ifstream& fin1, ifstream& fin2, ofstream& fout ); // <== you had this WRONG line //

mergeFiles( inputFile, inputFile2, outputFile );
David W 131 Practically a Posting Shark

I just remembered a previous example I did some time ago, with a simpler code ...

Take a look and you may see why I prefer this simpler (and more symetric) code.

// mergeTwoSortedFiles.cpp // 

// Note this example (safe) reads the files 
// *as strings
// *one number (one string) on each line ...
// *then converts each C++ string to a C string ...
// *then gets the int value of that C string using atoi

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib> // re. atoi

using namespace std;


const char* FILE_O = "file_o.txt"; // the output file //
const char* FILE_A = "file_a.txt";
/*
1
4
6
9
11
99
101
*/
const char* FILE_B = "file_b.txt";
/*
2
4
7
9
10
79
100
123
124
125
*/


void showFile( const char* fname )
{
    ifstream fin( fname );
    string line;
    int n = 0;
    while( getline( fin, line ) )
    {
        cout << " " << line;
        ++n;
    }
    cout << " n = " << n << endl;
    // fin.close(); // not really needed here ... since ...
                    // will be close when falls out of scope //
}


int main()
{
    ifstream finA ( FILE_A );
    ifstream finB ( FILE_B );
    ofstream fout ( FILE_O );

    if( finA && finB && fout )
    {
        string lineA, lineB;
        getline(finA, lineA);
        getline(finB, lineB);

        while( finA && finB )
        {
            if( atoi(lineA.c_str()) <= atoi(lineB.c_str()) )
            {
                fout << lineA << endl;
                getline(finA, lineA);
            } …
David W 131 Practically a Posting Shark

Yes ... using the STL set (or multiset) is sure a whole lot easier to code and use ... if your files will both fit into (available) memory :)

David W 131 Practically a Posting Shark

Does your program compile?
Are there errors?

Can you isolate (provide a small sample of code to illustrate where the error seems to be?)

(And when you copy/paste your code, to preserve the indentation, 'select' all the code, then press 'tab' before you submit it ... thus, the indents will be preserved and your code can be read.)

David W 131 Practically a Posting Shark

Hint ...
Try finding prime factors of each number,
then, gather up (multiply) all the common primes.