David W 131 Practically a Posting Shark

Does this help?

sum123 = sum1 + sum2 + sum3

David W 131 Practically a Posting Shark

A main goal here ... seems to be ...

to learn how to code an insertion sort ...

(of an array of prefixed size = MAX_ITEMS).

It doesn't really matter where the elements come from, to test out your insert (in sorted order) function.

Of course, if you are reading in numbers from a file, you would need to test if the 'array/list' is already full, before you try to insert a new element.

The little demo below ... may get you started ?

It uses C++ overloaded [] ... (instead of a Java type next() function.)

#include <iostream>

using namespace std;

/*
Hint: You may use either binary or linear search in 
    InsertItem( ), 
    DeleteItem( ) and 
    RetrieveItem( ).

In your main routine, the following tasks are required to complete:

Task 1: Create one instance of this class. 
You also need to read in data from one data file: 
float.dat, which contains the following numbers:
5.5
6.2
7.1
8.0
9.0
10.0
1.0
2.0
3.3
4.4

Data in float.dat contains floating numbers, 
which should be inserted into the object of SortedList. 

Note that you do not have any prior knowledge about data values in float.dat, 
but we assume that there are 10 elements in the data file.

Task 2: Use GetNextItem( ) to print out all the elements 
in the list in sorted sequence on computer screen.

Task 3: Use GetNextItem( ) to output all the elements 
in the list in sorted sequence onto a data file, output.dat.

Task …
David W 131 Practically a Posting Shark

From the instructions you supplied just now, it seems to me that your list is really just an array ... of MAX_ITEMS size.

And it would also seem that you are to insert each new item in sorted order, into that array, as long as there is room.

If the above is the case ... you need to start fresh, and code for that.

// if size 0 insert in first place, ++size
// else if not full
//    find insertion index 
//    if not top position
//       move all up one to make 'hole' at index
//       insert at index
//    else insert at top
//    ++size
//  else was full

l

David W 131 Practically a Posting Shark

I have to do a sorted list code according to some instructions.

What are the instructions?

Can you just use the STL list and the STL sort ?

or ...

Do you need to code your own class List and supply your own code to do a sort?

Even if you need to 'roll your own code' (bottom up) ...
it is often helpful to code the solution, firstly, using the STL ...

Then, when you have that all working well ... substitute in your own (pre-tested) list and sort.

Sorting a file, via reading it at first into a list, is conceptually very simple to code ... as this short demo of reading in a text file of 10 integers, indicates:

// listFromFileSorted/cpp //

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


using namespace std;

const char* FNAME = "myList.txt"; // example file to read and sort
/*
3 4 1 6 9 0 2 7 5 8
*/


void print( const list < int >& myLst )
{
    list < int > :: const_iterator it;
    for( it = myLst.begin(); it != myLst.end(); ++it )
        cout << *it << ' ';
}

int main()
{
    // read list from file
    ifstream fin( FNAME );
    if( fin )
    {
        list < int > myLst;
        int tmp;
        while( fin >> tmp )
            myLst.push_back( tmp );
        fin.close();

        cout << "Before sort ...\n";
        print( myLst );

        myLst.sort() ; // calls STL list sort

        cout << "\n\nAfter sort ...\n";
        print( myLst ); …
David W 131 Practically a Posting Shark

you could code it: while (rem_bal > 0.0)

Yes ... but then one still is using a 'double' to hold money ...

and cross-checks may NOT add to exact cent ...

since exact cents are not found/used at end of every calculation.

For working with money, always best to use exact (large) whole numbers.

David W 131 Practically a Posting Shark

You may like to look here ...

insert sort linked list

David W 131 Practically a Posting Shark

You know, the great thing about PC's is that YOU can quickly do some code changes and 'see' ...

// sortVecPointers.cpp //

#include <iostream>
#include <vector>
#include <algorithm> // for sort of vector elements ...

using namespace std;



ostream& operator << ( ostream& os,  vector< int* > v )
{
    vector< int* >::const_iterator it;
    for( it = v.begin(); it != v.end() ; ++ it )
        os << *(*it) << ' ';
    return os; 
}

/*
bool myCmp( const int* a, const int* b )
{
    return *a < *b;
}
*/

void showAddresses ( ostream& os,  vector< int* > v )
{
    vector< int* >::const_iterator it;
    for( it = v.begin(); it != v.end() ; ++ it )
        os << (*it) << ' '; 
}

int main()
{
    vector< int* > myPts;

    for( int j = 10; j > 0; -- j )
    {
        int* i = new int;
        *i = j;
        myPts.push_back( i );
    }

    cout << "Before sort ...\n";
    cout << "values at addresses " << myPts << endl;
    cout << "addresses \n"; 
    showAddresses( cout, myPts );

    //sort( myPts.begin(), myPts.end(), myCmp );

    sort( myPts.begin(), myPts.end() ); // Note: sorts address only ...

    cout << "\n\nAfter sort ...\n";
    cout << "values at addresses " << myPts << endl;
    cout << "addresses \n"; 
    showAddresses( cout, myPts );


    cout << "\n\n\nPress 'Enter' to continue/exit ... " << flush;
    cin.get() ;
}
David W 131 Practically a Posting Shark

This quick example may get you started on the right track ...

// sortVecPointers.cpp //

#include <iostream>
#include <vector>
#include <algorithm> // for sort of vector elements ...

using namespace std;



ostream& operator << ( ostream& os,  vector< int* > v )
{
    vector< int* >::const_iterator it;
    for( it = v.begin(); it != v.end() ; ++ it )
        os << *(*it) << ' ';
    return os; 
}

bool myCmp( const int* a, const int* b )
{
    return *a < *b;
}

int main()
{
    vector< int* > myPts;

    for( int j = 10; j > 0; -- j )
    {
        int* i = new int;
        *i = j;
        myPts.push_back( i );
    }

    cout << "Before sort ...\n";
    cout << "values at addresses " << myPts << endl;

    sort( myPts.begin(), myPts.end(), myCmp );

    cout << "After sort ...\n";
    cout << "values at addresses " << myPts << endl;


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

Don't forget to delete each new element ... when (finally) done with it.

David W 131 Practically a Posting Shark

I am a robotic student and very new in python programming. Here, I have a project to classify the type of robot. For example, a customer would like to buy a robot arm for their company. So, this project will aid them to select robot of their choices. First there will be a question such as " Hi sir, welcome to XXX Robot Factory""please choose the robot type for their specification" "a)arc welding b)grinding c)welding and d)laser cutting. Then, the customer will enter one key like (a) and the specification for the robot such as its price,load capacity and life will come out to show to the customer.Only these are my project and I have to use rule-base system [if..else statement] to meets its criteria. Can help me with this??

Python lends itself to just 'jumping in' and to start coding:

# print greeting ...
greeting = "Hi sir, welcome to XXX Robot Factory"
print( greeting )

# now do a main loop where you show menu
# get choice ... and then 'process' choice

menu = "a) arc welding\n" \
       "b) grinding   \n" \
       "c) welding    \n" \
       "d) laser cutting\n" \
       "x) exit this loop\n"

def doProcessA(): # dummies for now
    print( 'A' )

def doProcessB():
    print( 'B' )

while( True ): # start main loop
    print( menu )
    choice = input( "Your choice: " )
    if choice == "a":
        doProcessA()
    elif choice == "b":
        doProcessB() 

    # Note:these process functions
    # are to be yet …
David W 131 Practically a Posting Shark

@Anicia ... if you do really wish help, on your Python coding problem, please start a new thread and show what work (and code) that you have so far ... in the direction of solving the problem.

David W 131 Practically a Posting Shark

You can not have one function inside another function in either C or C++ languages. You can declare a function prototype inside a function, but the function itself has to be coded outside any other function.

I think that, the confusion here, may be that, in C++ classes, there are many examples of nested classes.

And there, in these nested classes, the functions can also be 'inline' ...

So ... '2teez' ... may be being confused ... by this?

Also ... the '2teez' may be aware that some programming languages DO permit 'nesting' functions .... and so ... may be confused because of that?

David W 131 Practically a Posting Shark

You wrote:

a && b if a is non-zero then b is false and not evaluated.

Not clear here ... what you mean.

For the expression (a && b) to be TRUE (non zero)

BOTH a and b must each be true.

If a if false, the b does NOT get evaluated ... since we KNOW that the expression MUST then be false ... no matter what the value of b might be.

a || b if a is non-zero then b is 1 then this true. I'm I correct?

If EITHER a or b are true ... then the result is true.

So ...
if a is true ... NO NEED TO evaluate b

However, if a is false ... then we MUST further see if b is true or false ... because the value of b will then determine the outcome.

David W 131 Practically a Posting Shark

In C++ ...

we commonly use 'cin' and 'getline' to get text ...

and we commonly use 'cout' to print text to the console.

These (iostreams) can be used in a user-defined function ... and often are ... in user defined functions with prototypes like:

bool loadFromFile ( const string& fileName, vector< string >& myStrings );

bool printToFile( const vector< string >& myStrings );
David W 131 Practically a Posting Shark
while (rem_bal!=0);

... is a problem, since ...

your running programm may never stop ...

since, the double value rem_bal may never be exactly zero.

When working with money, long long int ( or sufficently big integer value holding objects) ... is the way to go.

You want your values to be exact.

So always round ever calculation result to (perhaps the nearest) integer value ...

and store your money as 'cents' ... then can print formated (string?) output ... where you show the 2 decimal places ... with the value shown as dollars.

David W 131 Practically a Posting Shark

heyy all ,, i'm trying to get the middle word of sentence contains 3 words using find and substr ...

Do you really have to use 'find' and 'substr' ?

If not, as 'NathanOliver' has stated, using stringstream objects ... makes for a really nice C++ idiom here ...
(to extract the 2nd word, or all the words, in a line, [or file], of words ... )

I

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

using namespace std;


int main() // Note: C++ uses int main() and returns an int value //
{
    cout << "Enter a sentence :";
    string line;
    getline( cin, line );

    istringstream iss( line ); // construct iss object from line

    vector < string > myStrs; // construct empty vector to hold words

    string word;

    // ok ... can now extract all the 'words' from the line

    while( iss >> word ) myStrs.push_back( word ); // fill vector

    cout << "\nYou have " << myStrs.size() << " words in the line.\n";

    // can use [] operator ( or iterators)
    // to access the words in the vector

    // ... rest of code goes here ...

    cout << "\nPress 'Enter' to continue/exit ... ";
    cin.get();
}
David W 131 Practically a Posting Shark

what about the algorithm?

Hey man ...

promptText = "blablabla..."

TopOfLoop:
    input = getInput( withPromptText )
    if( ! valid( input ) ) goto TopOfLoop
    if( input == quit ) goto Stop
    getResultForInputAndShow( input );
    goto TopOfLoop


Stop:
David W 131 Practically a Posting Shark

You could handle it some thing like this:

void getPrimesInList( Clist* in, Clist* out )
{
    Node* cur = in->head;
    while( cur )
    {            
        if( isPrime(cur->value) )
            push_backClist( out, cur );
        cur = cur->next;
    }
}
David W 131 Practically a Posting Shark

Ok ... you got it working ... but ...

What about ... if the user enters non-numeric char's when an int is expected?

Try your program and see what happens?

Try your program (as it is) as a (void) function call ... and loop in 'main' as long as the user says 'more' ... and see what happens ?

The problems you will encounter, are both handled if ...

  1. you know how to loop until 'valid input' is obtained

  2. you know how to keep the stdin buffer 'flushed' after-input-when-ever-char's-may-be-left there still ...

See the below typical 'student type' way of dealing with the above two issues (and more) ...

/* guessNum.c */

#include <stdio.h>
/* #include <conio.h> */  /* don't use to keep code portable ... */
#include <stdlib.h> /* re. rand ... */
#include <ctype.h> /* re. tolower ...*/
#include <time.h> /* re. srand ... */

#define MY_BUF_SIZE 128 /* re. buf used to form prompt with sprintf */

const char* STATUS[] = { "Fantastic", "Amazing", "Excellent", "Wonderful", 
                         "Great", "Pretty Good", "Not too bad", "That's ok",
                         "You finally got it", 
                         "Maybe better ... next time."  } ;


/* a simple student way to handle numeric input ...
   so program won't crash on bad input */
int takeInInt( const char* msg, int myMin, int myMax )
{
    int good = 0, val = 0;
    while( !good )
    {
        printf( msg ); fflush( stdout );

        if( scanf( "%d", &val ) == 1 && getchar() == '\n' )
            good = …
David W 131 Practically a Posting Shark

What is the difference between these ... ?

a)

    //Convert and check if we have a valid data
    for(i=0; i<len; ++i)
    {
        value=buffer[i] - '0';
        if (value < 0 && value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }
        total = (total*8)+value;
    }
    printf("Decimal equivalent is: %d\n", total);

b)

    //Convert and check if we have a valid data
    for(i=0; i<len; ++i)
    {
        value=buffer[i] - '0';
        if (value < 0 || value > 7)
        {
            printf("Invalid octal data\n");
            return;
        }
        total = (total*8)+value;
    }
    printf("Decimal equivalent is: %d\n", total);

Hint:

What is the difference between the truth of

a && b // (a and b)

vs

a || b // (a or b)

?

Also... just THINK!

Can the result of (value < 0 && value > 7)

EVER BE TRUE (for ANY value) ?

David W 131 Practically a Posting Shark

please edit above line 78, 79 to ...

 cout << "asciihex2int( '" << line[0] << "' ) = "
      << asciihex2int( line[0] ) << endl;

so that the 'original char' is used there.

David W 131 Practically a Posting Shark

Did you mean ... a short hex char to int conversion ?

// ascii_hex_char_2_int.cpp //

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

#include <iostream>
#include <string>

using namespace std;

/*
48  060 30  00110000    0   
49  061 31  00110001    1   
50  062 32  00110010    2   
51  063 33  00110011    3   
52  064 34  00110100    4   
53  065 35  00110101    5   
54  066 36  00110110    6   
55  067 37  00110111    7   
56  070 38  00111000    8   
57  071 39  00111001    9

65  101 41  01000001    A   
66  102 42  01000010    B   
67  103 43  01000011    C   
68  104 44  01000100    D   
69  105 45  01000101    E   
70  106 46  01000110    F   

97  141 61  01100001    a   
98  142 62  01100010    b   
99  143 63  01100011    c   
100 144 64  01100100    d   
101 145 65  01100101    e   
102 146 66  01100110    f   
*/

// Shortest? function to convert an ascii hex digit (CHAR) 
// to *AN INTEGER* 0..15.
//
//      ( assumes a valid hex digit CHAR IN RANGE: 
//        '0'..'9', 'A'..'F', 'a'..'f' )
int asciihex2int( char ascii )
{
    if( ascii > 0x40 ) // HANDLES: 'A'..'F' and 'a' .. 'f'
        return (ascii & 0x0f) + 9 ; // (ascii & 0x0f) returns 1..6

    return ascii - '0'; // '0' .. '9'
}


bool more()// defaults to 'true'/'yes' ... unless 'n' or 'N' entered
{
    cout << "\nMore (y/n) ? " << flush;
    int reply = cin.get();
    cin.sync(); // 'flush' cin stream ...
    if( reply == 'n' || reply == 'N' ) return …
David W 131 Practically a Posting Shark

The first step in solving a problem is a clear statement of what is required.

You wrote this at the top:

... been facing this problem for days ... have written a program where ... suppose to read a specific number of lines

within different intervals

What does this

within different intervals

mean?

Does it mean, as you read a file, line by line, counting the lines, from say line 1 as the first line ...

that you are take some (user specified) 'sample of lines' ... say lines n to line (n+size-1)

(You could copy these lines into a tmp vector of lines ... and pause your file scanning while you process that tmp vector ...)

and count the number of occurance of r and s

Ok ... process that tmp vector of lines, and report

and then divide r by s.

If that is 'your problem' ... can you see now that it is easy to handle it this way?

David W 131 Practically a Posting Shark

It seems you were trying to show a MENU with 4 choices ...

To print a big (graphic) letter,

Choices are: Z or T or N or X

Rather than a switch and case ... sometimes a TABLE is nicer :)

// bigLetters.cpp //


#include <iostream>
#include <string>

#include <cstdlib>

using namespace std;

const char* zz = " ------- \n" \
                 "       / \n" \
                 "      /  \n" \
                 "     /   \n" \
                 "    /    \n" \
                 "   /     \n" \
                 "  /      \n" \
                 " /       \n" \
                 " ------- ";

const char* tt = "---------\n" \
                 "    |    \n" \
                 "    |    \n" \
                 "    |    \n" \
                 "    |    \n" \
                 "    |    \n" \
                 "    |    \n" \
                 "    |    \n" \
                 "    |    ";

const char*  nn = "          \n" \
                 "|\\       |\n" \
                 "| \\      |\n" \
                 "|  \\     |\n" \
                 "|   \\    |\n" \
                 "|    \\   |\n" \
                 "|     \\  |\n" \
                 "|      \\ |\n" \
                 "|       \\|";

const char* xx = "\\       /\n" \
                 " \\     / \n" \
                 "  \\   /  \n" \
                 "   \\ /   \n" \
                 "    /\\    \n" \
                 "   / \\   \n" \
                 "  /   \\  \n" \
                 " /     \\ \n" \
                 "/       \\";


const char* letters [] = { zz, tt, nn, xx };

int main()
{
    for( ; ; )
    {
        cout << "Choose 1-z, 2-t, 3-n, 4-x \n"
             << "Your choice 1..4 :" << flush;
        string line;
        getline( cin, line );

        if( !line.size() || line[0] < '1' || line[0] > '4' )
        {
            cout << "\nInvalid ... try again ...\n";
        }
        else
            cout << "Your choose: \n\n" << letters[ line[0] - '1' ]
                 << endl;

        cout << "\nMore (y/n) ? " << flush;
        getline( cin, line );
        if( line.size() && (line[0] == 'n' || line[0] == 'n') )
            break;

        cout << endl;
    }

    return 0;
}
David W 131 Practically a Posting Shark

If your data file has validated data ... all like this:

500 - 1000 : 29
1000 - 1500 : 0
1500 - 2000 : 0
2000 - 2500 : 0

And, if all that you want is the int value at the end,
(or possibly you want to fill a vector of struct with all the data) :

ifstream fin( "yourFileName.txt" );
if( fin )
{
    string s[5];
    vector< int > myVec;
    while( fin >> s[0] >> s[1] >> s[2] >> s[3] >> s[4] )
    {
        myVec.push_back( atoi( s[4] );
    }
    fin.close();
    // use data in vector
}
else // handle error
David W 131 Practically a Posting Shark

You may like to see this revision ...

  1. that uses functions ...
  2. that takes in ('crash safe') string input
  3. that validates the input, in a loop, until valid
  4. that demos using the same function in different ways, via a 'flag' variable ... also, 'default values'
  5. that uses arrays ... so program can be made generic
  6. that uses a 'data struct' ... and an array of struct
    ... and '[i]' and '.' notations
  7. that uses Global constants so that the program can be easily revised to handle more than (array of size) 3
    etc...

See the added comments and note use of descriptive variable names ... to help 'self document' the code.

Enjoy ...

// top3Employees.cpp //

#include <iostream>
#include <string>
#include <sstream> // re. stringstream obj's
#include <cctype> // re. isdigit, toupper

using namespace std;


// can easily change these 2 GLOBAL constants, here, 
// to update whole program ...
const int MAX_NUM = 3; 
const string POSITIONS[] = { "1st", "2nd", "3rd" } ;

struct Employee
{
    string name;
    string data;
} ; // <- to tell compiler that the struct end is reached  //


// type 1: to be VALID, string MUST have 4 chars only, each a digit! 
// type 0: to be valid, sting must be NON empty ... (default type is 0)
bool isValid( const string& s, int type = 0 )
{
    if( type == 1 )
    {
        if( s.size() == 4 )
        {
            for( int i = 0; …
David W 131 Practically a Posting Shark

You can try an updated Dev ... has C++11 ... also 32 or 64 bit

Dev now has C++11

David W 131 Practically a Posting Shark

Have you tried to Google for any examples?

But here is one link that my be helpful, if you need one more example?

A linked list ... with nested class iterator, etc

6 steps

David W 131 Practically a Posting Shark

Hey John,

if you really wish to learn to code in C++ and / or C, you have one really great thing going for you, that all programmers need ...

i.e. great persistance :)

Once you have a good grasp on some basics ... things like how to keep the stdin buffer flushed (or in C++ ... the cin stream ... flushed) ... and input validation ... and getting a feel for scanf and fgets (or in C++, cin and getline) ... and a few other basics ... you WILL BE WELL on your way.

Just write a lot of code ... bottom up ... in small steps.

Make sure, that at each step, your code compiles and gives all the EXACT expected output, that you wanted that program code to produce ...

Then add a small next block of code,
compile,
debug,
etc until you get the EXACT output desired.

(Or if you always keep a copy of your previous working step, and you simply can-not find the bug(s) in this next step, just go back and start coding fresh from the last working stage of developement.)

With all the helpful info on the web so accesible these days, once you have a few basics well understood, you can then make rapid progress ... but only if you UNDERSTAND what each code snippet is doing and why it is used.

The joy of computing, these days, once you get some basics inderstood, is that you can …

David W 131 Practically a Posting Shark

Can't really check ... since some stuff missing ... too many problems to compile ...

Turn all your compiler errors / warnings on ...

See the changes / comments here / compiler warnings here

they may help ?

... may get you stated on debugging your code ?

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

    typedef int kintyr;

    typedef struct 
    {
        int qFault;
    } Fault ;

    typedef struct {
        struct qElem *prv;          
        kintyr *dat;                    
        int *priority;
    }qElem;


    typedef struct {
        qElem *fr,*bk;              
        int cnt;                    
    }que;



    que *qNew( Fault* f )
    {
        que *q = malloc(sizeof( que )); /* fixed ??? */

        if (q==NULL)
            return NULL;

        q->fr = NULL;
        q->bk = NULL;
        q->cnt = 0;


        /* qFault = 0; // what is this ... not used here anyways */
        f->qFault = 0;

        return q;
    }

    que *qEnq(que *q, kintyr *x, int *prrt, Fault* f )
    {
        qElem* new;

        /* que *zn=q; // NOT use here ??? // */
        /* qFault = 0; */
        f->qFault = 0;
        if (q == NULL)
        {
            /* qFault = 1; */
            f->qFault = 1;
            return q;
        }
        /* // can't check this WITHOUT having function qCHK 
        if (qCHKf(q) == 1)
        {
            // qFault = 3; //
            f.qFault = 3;

            return q;
        }
        */
        /* qElem *new = malloc(sizeof(*new)); */
        new = malloc(sizeof(*new));

        new->prv = NULL;
        new->dat = x;
        new->priority=prrt;

        if (q->fr == NULL || q->fr->priority>prrt  ) 
        {
            new->prv=q->fr; /* ??? */
            q->fr = new;

        }
        else
        {
            que *tempas=q;
            while(tempas->fr->prv!=NULL && tempas->fr->priority<=prrt)
                 tempas=tempas->fr; /* ???  */ 

            new->prv=tempas->fr; …
David W 131 Practically a Posting Shark

Some times the very beginning steps of computer programming seem 'very hard' ... but like learning any new complex thing ... once you 'see' how it works ... and 'how to make it work' ... you are well on your way :)

The tricky part (at first with using scanf for input), is to remember that it needs the ADDRESS, passed in, of the variable(s) passed into the scanf function, in order that THAT VERY SAME variable gets updated in the 'calling scope'.

There are many many examples on the web ... (Google 'C scanf' and see) ...

But you may like to take a look at the examples here:

6 fast steps in C

Once you understand well, a few basics, programming can become very enjoyable ... if you like 'problem solving'.

David W 131 Practically a Posting Shark

When you begin computer programming ... don't leave your 'normal thinking skills' ... behind.

How is the series 2,4,6,8, ...
related to        1,2,3,4, ..

.

Answer: ?

How could you design a program for this?

Or ... if you start with 2
What can you keep adding to the previous value(s) ...
So that you get ... 4,
                    6,
                    8,
                    ... etc

Can you code this in C?

David W 131 Practically a Posting Shark

Also ... interesting spelling :)

#include <stdio.h>
/* #incluede <string.h> */ /* that's how I feel sometimes :) */
#include <string.h>


void getnames( char name[][50], int num ) ;
void getnames2( char name[][50], int num ) ;
void shownames( char name[][50], int num ) ;



int main()
{
    char name[5][50];

    int numofnames = 5;
    getnames( name, numofnames );
    shownames( name, numofnames );

    getnames2(name, numofnames );
    shownames( name, numofnames );

    return 0;
}      



void getnames( char names[][50], int numofnames )
{
    int i;
    char r;
    printf( "Note: leading spaces, when using "
            "'scanf' input, will be 'skipped' ...\n\n" );

    for( i = 0; i < numofnames; ++ i )
    {
        printf( "With NO tabs or spaces, "
                "enter a name %d: ", i+1 ) ;
        scanf( "%49s", names[i] );

        /* now could 'flush' stdin ... */
        while( scanf("%c", &r) && (r != '\n') ) ; /* 'flush' ... */

    }
}

void getnames2( char names[][50], int numofnames )
{
    int i;
    char* p;
    printf( "Note: leading spaces, when using "
            "'fgets' input, will NOT be 'skipped' ...\n\n" );

    for( i = 0; i < numofnames; ++ i )
    {
        printf( "Tabs & spaces ok here, "
                "enter a name %d: ", i+1 ) ;
        fgets( names[i], 50, stdin );

        /* fix up fgets ... */
        p = strchr( names[i], '\n' );
        if( *p ) /* if( *p = 0 ) */
            *p = 0; /* overwrite '\n' char at end ... */
        else
            while( getchar() != '\n' ) ; /* 'flush' ... */

    }
}

void shownames( char names[][50], int numofnames ) 
{
    int i;
    for( i = 0; i < numofnames; ++ i )
        printf( "%s\n", names[i] );
}
David W 131 Practically a Posting Shark

If you would like some ideas about coding / using big Integers, this link may give you a start ...

Big Numbers

Also, you may like to know that Python comes with big integers ... (and big decimal precision also) ... so you may like to consider doing your program in Python?

David W 131 Practically a Posting Shark

Looks like a fun project ... can you code a working shell to get started?

Announce what the program is about
Ask for (validated) input
Call a function, passing in input value, print output
Ask if want to loop again?

David W 131 Practically a Posting Shark

Do you already have a string class to work with?

If NOT, you seem to be off on the wrong track ... ?

A common student problem is to build ... bottom up ... a class String ...

perhaps using a (dynamically allocated) C char string inside ...
(a 0 terminated block of char's as the private data member of the class String)

... and in your case, this class String is also to implement:

2 versions of strncat
2 versions of strcat
2 versiona of strncpy
2 versions of strcpy

?

If you were do some Google searching, you could find several examples of a C++ String class, to give you some ideas ... to help you get started on the right track.

Take a look at this 'shell' ... just a start ...

examples

// test_newBase_String.cpp //  // 2014-03-12 //

 /* *** This may? give you some idea how to start ***


    http://www.4shared.com/folder/xPqGQHPl/class_String.html


    two versions of each of the string concat functions 
    (strcat, strncat) 

    and string comparison functions 
    (strcmp, strncmp)

    Since there are two versions of each function that you will build, 
    make sure that one version is done using array subscripting 
    and the second uses pointers and pointer arithmetic. 

    Array subscripting means that you will treat everything in your code 
    like an array (use brackets instead of the asterisk) 

    whereas pointer arithmetic means everything will be treated as a pointer 
    (you will use the asterisk instead of array …
David W 131 Practically a Posting Shark

Now re. your distance between two cities problem, you like to see the list and vector examples here ...

CitiesListType_sort3.cpp

CitiesVectorType_sort3.cpp

list or vector type

David W 131 Practically a Posting Shark

Please see my recent post in the C forum, that shows an easy way to submit code and preserve the indentation.

KEEP indentation

A copy below:

It seems you still have NOT mastered a 'basic' here at Dani... i.e. submitting code in such a way as to preserve the indentation formatting ...

Please learn how ... right away!

The way I do it ... is like this:

->select and copy your source code (as you do already)

->click on the < / > Code > icon at the top of the Dani submit window ... and that opens up a submission window

->at the top of your web browser click on Edit and then paste the code you selected and copied into that Dani code submission window

->at the bottom of the Dani code window click on the accept icon

Now you will see all your code indented (one tab in more) ... and with all the original indentations preserved.

After checking that it worked ok ... you can submit
(and edit, it again for about the next 1/2 hour if changes are needed.)

Here is a recent student request ... reworked a little ... to show the ease of moving between STL containers ... (if you use iterators ... and typedef the container used.)

This may give you some ideas HOW (easy it is) to convert from a list to a vector (using iterators) ... and then, if you wish ... you can further …

David W 131 Practically a Posting Shark

It seems you still have NOT mastered a 'basic' here at Dani... i.e. submitting code in such a way as to preserve the indentation formatting ...

Please learn how ... right away!

The way I do it ... is like this:

->select and copy your source code (as you do already)

->click on the < / > Code > icon at the top of the Dani submit window ... and that opens up a submission window

->at the top of your web browser click on Edit and then paste the code you selected and copied into that Dani code submission window

->at the bottom of the Dani code window click on the accept icon

Now you will see all your code indented (one tab in more) ... and with all the original indentations preserved.

After checking that it worked ok ... you can submit
(and edit, it again for about the next 1/2 hour if changes are needed.)

Also, it seems that you have a very old compiler that assumes that an 'int' size is 16 bits wide ...and an 'unsigned int' size is also ... 16 bits wide.

If that is the case ... you will not easily be able to access 32 bit wide values to work with ...

so just limit your values (in and out) to fit into a 16 bit (unsigned int) number like this, ...

(The examples below use your old Turbo C++ style of coding, and were checked, and compiled, error free, …

David W 131 Practically a Posting Shark

And when you hit the next letter ...

i.e. when you reach B after printing all the A's ...
print a blank line

You may need to first switch to UPPER case every first letter in the names ... if some were entered with lower case first letters ... and then do the sort ... before you attempt the above.

If you can't easily access the info for each data record,

i.e if better to NOT write to file as one long string ...

you may need to use a struct and write each member on a separate line

and then read back, filling up a struct, and add each struct to a vector (or what ever STL container you prefer) as you go.

David W 131 Practically a Posting Shark

You may like to see this ref link to the sorts that already come in the C++ library

library sort

The example at the above link is for sorting a vector of integers.

Below is an example of sorting a C++ STL list of C++ strings:

// sort_list_of_string.cpp //

#include <iostream>
//#include <algorithm>  // not needed for list sort
#include <string>
#include <list>

using namespace std;

ostream& operator << (ostream& os, const list< string >& ml )
{
    list< string >::const_iterator it;
    for( it = ml.begin() ; it != ml.end() ; ++ it )
         os << *it << ' ';
    return os;
}

bool myLenCmp( const string& a, const string& b )
{
    return a.size() < b.size() ;
}


int main ()
{
    list< string >  myList; // construct an empty list ...

    myList.push_back( "Joe" );
    myList.push_back( "Sue" );
    myList.push_back( "Annie" );
    myList.push_back( "Zoe" );
    myList.push_back( "Lynne" );

    cout << "myList unsorted: \n"  << myList << endl;

    // call list sort and compare strings in dictionary order

    myList.sort();

    cout << "myList dictionary sorted: \n"  << myList << endl;

    // call list sort and compare strings in len order

    myList.sort( myLenCmp );

    cout << "myList length sorted: \n"  << myList << endl;

    return 0;
}
David W 131 Practically a Posting Shark

Yes ... you could use a vector (instead of a list) ...

But using iterators makes your code much easier to re-code (to use a vector or to use other STL containers ...)

Also ... if you are doing a lot of deletes ... using a list container makes the deletes very efficent.

This example illustrates a way to organize a project ...

Click Here

David W 131 Practically a Posting Shark

Just a variation on the theme... (for your enlightment and enjoyment) ...

Note the simple looping exit condition ...

The loop is exited when a cin error flag is raised by any invalid (here, any NON non-numeric) input ...

#include <iostream>
#include <iomanip> // re. formatting output ...
#include <string>

using namespace std;


int main()
{
    // set output to 2 decimal places ...
    cout << fixed << setprecision(2) ;

    const string prompt = "Enter the length of steel "
                          "bars bought (q to quit) : ";
    const int flat = 1000;
    const int min_len = 2;
    int length;

    // begin entry loop ... until 'q' ...
    // i.e. loop until any cin error here ... is reached
    while( cout << prompt << flush &&
           cin >> length && cin.get()  == '\n' )
    {
        double discFraction = 0;

        if( length >= 100 ) discFraction = .25;
        else if( length >= 80 ) discFraction = .20;
        else if( length >= 60 ) discFraction = .15;
        else if( length >= 40 ) discFraction = .10;
        else if( length >= 20 ) discFraction = .05;

        if( length >= min_len )
        {
            double total = flat * length;
            double disc = total*  discFraction;
            double discPercent = 100 * discFraction;

            cout << "\nTotal before discount :  $"
                 << setw(10) << total
                 << "\nDiscount              :  $"
                 << setw(10) << disc
                 << " (" << discPercent << "%)"
                 << "\nNet due               :  $"
                 << setw(10) << total - disc << endl;
        }
        else
            cout << "\nMinimun stock size is " << min_len;

        cout << "\n\nNext order ... \n\n";

    }

    cout << "\nQuitting ... " << flush;

    return 0;
}
Mart_webber commented: Thanks David +0
David W 131 Practically a Posting Shark

If you look at this table:

BASE     Dig Max Decimal String rep (note string len = Dig col value)
=======  ==  ==========  ================================
base  2, 32, 4294967295, 11111111111111111111111111111111
base  3, 21, 4294967295, 102002022201221111210
base  4, 16, 4294967295, 3333333333333333
base  5, 14, 4294967295, 32244002423140
base  6, 13, 4294967295, 1550104015503
base  7, 12, 4294967295, 211301422353
base  8, 11, 4294967295, 37777777777
base  9, 11, 4294967295, 12068657453
base 10, 10, 4294967295, 4294967295
base 11, 10, 4294967295, 1904440553
base 12,  9, 4294967295, 9BA461593
base 13,  9, 4294967295, 535A79888
base 14,  9, 4294967295, 2CA5B7463
base 15,  9, 4294967295, 1A20DCD80
base 16,  8, 4294967295, FFFFFFFF
base 17,  8, 4294967295, A7FFDA90
base 18,  8, 4294967295, 704HE7G3
base 19,  8, 4294967295, 4F5AFF65
base 20,  8, 4294967295, 3723AI4F
base 21,  8, 4294967295, 281D55I3
base 22,  8, 4294967295, 1FJ8B183
base 23,  8, 4294967295, 1606K7IB
base 24,  7, 4294967295, MB994AF
base 25,  7, 4294967295, HEK2MGK
base 26,  7, 4294967295, DNCHBNL
base 27,  7, 4294967295, B28JPDL
base 28,  7, 4294967295, 8PFGIH3
base 29,  7, 4294967295, 76BEIGF
base 30,  7, 4294967295, 5QMCPQF
base 31,  7, 4294967295, 4Q0JTO3
base 32,  7, 4294967295, 3VVVVVV
base 33,  7, 4294967295, 3AOKQ93
base 34,  7, 4294967295, 2QHXJLH
base 35,  7, 4294967295, 2BR45QA
base 36,  7, 4294967295, 1Z141Z3
Enter the base for the number to be converted:

Click Here

You can see the max string rep for each base, 2..36, if the the decimal max storage size is a 32 bit unsigned int

David W 131 Practically a Posting Shark

How does the above question, relate to your original thead here:

I want to create a queue that holds certain information.

I want it to hold multiple peices of information like below.

Name, Age, Race, Sex.

How can i create a queue FIFO. that holds multiple pieces of information like this that i can access or add into?

Are you asking about coding, bottom up, your own class Queue?

If not, please start a new thread for a new topic.

David W 131 Practically a Posting Shark

Have you done a web search on "C++ file handling" ?

Then try out some code to create a simple text file of data lines

Then read those lines back in (from the above file) and show them as you read each line

These are the basics you will need to master ... at first.

David W 131 Practically a Posting Shark

... code so that the user can choose a math operation and ... have that type of operation(either add sub mult or divide) run as much as a user wants ... Say, if the user wanted 5 addition questions only.

And how do I keep track of the correct ... ( ++counterCorrect )

I would suggest you start fresh with a shell that does just the essence of what you want ...
// the shell could just include all the comments listed below ...
//and give some simple output ...
//to verify you GET that expected output!!!

Compile and debug that at FIRST!

THEN ... and ONLY THEN ...
fill in the sections of that shell
section by section ...

test and debug each section INDIVIDUALLY
(perhaps ... some of the code blocks in your example code may do, or guide you in coding to do, a job requested) ...

USE a separate function for each job ...
(add, sub, mul, div)

//TopOfLoop:

//show menu

//prompt and input choice

//prompt and input the number of questions to show and get answered

//do the job (function) requested, presenting then, the number of questions requested, and counting the number of correct answers as you go

//then report all the results

//the kind of job ...
//the number of questions
//the number correct

//prompt and ask if more ... 
//i.e. do you want to loop again from top
David W 131 Practically a Posting Shark

Oops ... I think you meant to use ...

int main()
{

   /* your code ... */

   return 0;

}
Ancient Dragon commented: yes +14
David W 131 Practically a Posting Shark

Firstly ... you need to recode each class into two files:

The .h file with appropriate 'guards' (prototypes)
and ...
The .cpp file ... (include .h files needed, and any other library header definition <header_file> needed.)

Then compile main() ... as a project ... with includes (of any headers needed.)

David W 131 Practically a Posting Shark

But ... the first part (of the 2nd step) ... is to get the first program (stage) ... working ... the way you wish.

See this example, for a common student way to handle input validation ...

// checkBook1.cpp //

// edited ... with input validation added, etc...

/*
Write a C++ program to help you balance your checkbook at
the end of the month. The program should have the user enter
the initial balance followed by a series of transactions.
For each transaction, first have the user enter a transaction
type. The valid transaction types are:

C - process a check.
D - process a deposit.
E - do end of month processing and exit the program.
For checks and deposits, the user should be prompted to
enter the transaction amount.

Service Charges

There is a $0.25 service charge for each check written.
Keep a running total of the service charges.
Service charges are not deducted from the account balance
until the end of the month.
Output

After each transaction, print

the command data (to confirm the transaction)
the resulting account balance
the total service charges accrued so far
*/

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

using namespace std;

// if place these two Global constants here...
// program can be easily updated (here, at top)
const char* MENU =
    "Please enter a transaction code.\n" \
    "C - Process a Check.\n" \
    "D - Process a Deposit.\n" \
    "E - Do end of month processing …
David W 131 Practically a Posting Shark

Nice :)

In C++, why not rather use C++ (safe) strings?

// in C++ ... why not use (safe) C++ string   ?

#include <iostream>
#include <string>
#include <queue>

struct Person
{
    const std::string name;
    int age;

    Person( const std::string& n="", int a=0 ): name(n), age(a) {}
    friend std::ostream& operator << ( std::ostream& os, const Person& p )
    {
        return os << p.name << ", age " << p.age;
    }
} ;


int main() 
{

    std::queue < Person > pq;
    pq.push( Person( "David", 66 ) );
    pq.push( Person( "John", 20 ) );

    Person front = pq.front();

    std::cout << "I am " << front << std::endl;

    return 0;
}