David W 131 Practically a Posting Shark

This example may give you some ideas how your above code could be re-coded using C++ idioms (and not Java idioms) ...

// insertSortedAryList.cpp //

#include <iostream>
#include <fstream>
//#include <string>

using namespace std;


#define show 0 //set to 1 to turn ON 'showing...'//

const int MAX_ITEMS = 100; // need = at least 13 here ... //
const char* FNAME = "float.txt";
const char* FNAME_OUT = "float_sorted.txt";
/*
10.3 11.2 12.7 0.8 -3.2 11.7 -22.9 -1.1 9.9 -111.1 999 -999 0
*/


typedef float ItemType;
typedef ItemType* iter;
typedef const ItemType* const_iter;

class SortedList
{
public:

    SortedList() : length(0) {}

    int size() const  { return length; }

    void clear() { length = 0; }

    bool insert( const ItemType& x )
    {
        //cout << "length = " << length << endl;
        int i = 0;
        if( length < MAX_ITEMS )
        {
            if( length )
            {
                i = findInsertIndexBinSearch( x );
                if( i < length )
                {
                    // open up hole at index i
                    for( int hole = length; hole > i; --hole )
                    values[hole] = values[hole-1];
                }
            }
            values[i] = x;
        }
        else
        {
            cout << "\nList was FULL! NO room to insert!\n";
            return false;
        }
#if show
        cout << " at index[" << i << ']' << endl;
#endif
        ++length;
        return true;
    }

    bool erase( const ItemType& x )
    {
        bool wasDeleted = false;
        int i = foundAtIndexBinSearch( x );
        if( i >= 0 )
        {
            // copy down over item at index index i
            for( int j …
David W 131 Practically a Posting Shark

You could try something like this ...
(that uses the code given you by @Gribouillis ... slightly revised ... and with comments added that may help explain it for you.)

filename = 'myData.txt'
'''
07 13 14 23 45 - 04
13 27 34 41 47 - 49
22 24 45 46 51 - 15
10 14 22 23 42 - 13
01 04 17 31 52 - 38
12 23 40 47 57 - 04
'''

def score(i, t): # i = items_set, t =target_set
    # returns number of items in intersection set of target & item sets
    # also returns True or False indicating if the last items match
    return ( len( set(i[:5]) & set(t[:5]) ), i[-1] == t[-1] )

import fileinput as fin

text1 = '(Number of Items in Intersection,'
text2 = ' Last Items do Match?)'
stars = [ ' *' for i in range(5) ] + [ '-', ' *']

i = 0
for line in fin.input( filename ):
    items = line.split()
    if i == 0:
        target = items
        print( 'Target' )
        print( items )
        print( '\nItems', ' '*4, text1, text2  )
        print( stars, ' *, ***** ' )
    else:
        print( items, score(items, target) )
    i += 1

input()
David W 131 Practically a Posting Shark

Very creative ... :)

-> using pre-fixed length C strings ... (Not a good idea usually...in designing a C++ string class ?)

-> some curious stuff ... that I am surprized that you even got compiled and then to have any good output ?

BUT ... please turn on your COMPILER error warnings ... so you can see what to fix ... and then ... look at the example below ... and see all the embedded comments ... to see the way a typical student class String ... is (normally) expected to look ...

// student_classString.cpp //

/*
    okay,. so far am to this point,. 
    i have managed to do a version of strcat which include a 
    array and a pointer,. 
    but i still have problems with the other function..
*/

/*
    Ok ... you seem to be needing a little nudge in the
    'right direction' ... to get started
    please lookup or Google 'the big 3 of C++ classes' ... 
*/


#include <iostream>
#include <cstring> // re. strlen

using namespace std;


class MyString
{
public:
    MyString();
    ~MyString(); // 1... of 'BIG THREE' ... needed here

    // copy ctro...
    MyString( const MyString& ); // 2... of 'BIG THREE' ...

    // ALSO, need to have ...
    // ctor from passed in C string ... 
    // (so can construct fron C strings)
    MyString( const char[] );

    // overloaded assignment ...
    MyString& operator = ( const MyString& ); // 3... of 'BIG THREE' ...

    MyString& concat( const char[] );
    MyString& concat( const …
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 may like to look here ...

insert sort linked list

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

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

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

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

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

Here is a common 'show data' example ... that may help you to get started ... ( Oops ... looks like I missed the post just now of Dani's 'Ancient Dragon' :)

// twoArrays.cpp //

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

using namespace std;

const int NUM_COMPANIES = 6;

const int NUM_COLS = 4;

void print( const string[], const int[][NUM_COLS], int size );


int main()
{
    string companies[] = {"SDF","VXC","CCL","REL","MPL","GHB"};

    int sales [][NUM_COLS] =
    {
        {10000, 70000, 60000, 80000},
        {35000, 55000, 34000, 60000},
        {35000, 46000, 17000, 29000},
        {29000, 30000, 31000, 38000},
        {42000, 44000, 46000, 45000},
        {20000, 23000, 35000, 43000}
    };

    cout << setw(10) << "Company"
         << setw(10) << "sales1"
         << setw(10) << "sales2"
         << setw(10) << "sales3"
         << setw(10) << "sales4" << endl;

    print( companies, sales, NUM_COMPANIES );

    cin.get();
}


void print( const string co[], const int sales[][NUM_COLS], int size )
{
    for( int i = 0; i < size; ++i )
    {
        cout << setw(10) << co[i];
        for( int j = 0; j < NUM_COLS; ++j )
            cout << setw(10) << sales[i][j];

        cout << endl;
    }
}
David W 131 Practically a Posting Shark

Will you be reading back from file to fill arrays?

David W 131 Practically a Posting Shark

It looks like you have 6 companies ...

And sales for 4 periods for each company ?

This lends itself to a (data) struct
using ONE array of struct (or better a C++ vector of struct)

(NOT 2 arrays ... that is 'old-school'!)

struct MyBus
{
   string name;
   double[4] sales;
} ;

where you could use a file data structure like this

sales1 sales2 sales3 sales4 company name till end
next lines ... as above ...

to write the data for each company all on one line

Then ... the read back is easy ... just read the lines and parse each line using stringstream ...to fill each struct

Note:
your file structure might begin with a line holding the number of companies to be read

then followed by a line holding the number of sales periods for each company

then all the data lines would follow.

David W 131 Practically a Posting Shark

I just noticed ... that you have posted the very same problem at ... at least two other help sites ...

That is NOT the way to learn how to program ... looking for some-one to give you the code !!!

BUT ... I have ALREADY given you an unique algorithm to solve your 'problem' ... that uses a 'struct' ... and that first validates user input, etc.

However, the code that you show me back, each time ... shows NO evidence, what-so-ever, that you have studied or tried to implement that algorithm ... or any validation features ... and the code you show me back also uses fixed length C strings, with the max length pre-fixed at compile time ... not any variety, (that I can see), of C++ string.

If you do not wish to learn how to code ... for yourself ... in C++ ...why should I bother further ... to give away insights, that were very costly for me ... both in time and work ... for me to acquire ???

David W 131 Practically a Posting Shark

Here is an example ... (that instead of using C++ string, includes its own class String ... the same class String that I supplied you the link to ... above.)

Note: the sort would be faster (more efficent) if the vector, after input of a line (String) held (at input) Items (stuct) ... formed then, instead of formed from strings ... while sorting, in the compare function.

// 2_test_sortAlpahNum.cpp // // 2014-03-04 //

// tests out class String etc... //

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


// for 'quick/cheap' test ... use these includes below ... //

#include "base_string.cpp"
#include "string.cpp"

//#include "case.cpp" // NOT used here
//#include "reverse.cpp"  // NOT used here

////////////////////

#include <iostream>
#include <fstream>
//#include <sstream> // not used here now with this class String ...
//#include <string> // using above class String

#include <vector>  // NEED STL vector ... (OR some STD like, vector class included)

#include <algorithm> // Need STL re. sort
#include <ctype.h>    // re. isdigit, isalpha, tolower // Modern C++ uses <cctype> //
#include <stdlib.h>  // re. atoi // Modern C++ uses <cstdlib> //

using namespace std; // Modern C++ has and uses namespace //



typedef vector< String > VecStr; // Note: using STL vector BUT above class String

// takes in whole line ... returns int value of 1st char ... or zero
int takeInChar( const String& msg ) // In C/C++ char's have int values ...
{
    cout << msg << flush;
    String reply;
    getline( cin, reply );
    if( reply.size() ) …
David W 131 Practically a Posting Shark

I do not have your non-standard version of C++ string...
So how can I help you with it?

David W 131 Practically a Posting Shark

Need some help ASAP, so I emailed my teacher to verify my code and this is what he said:

"There is so much wrong, it is hard to know where to start.

Yes ... and the place to start is with an up-to-date C++ compiler and an up-to-date C++ course that uses present day C++ standard code.

You had a functioning library and driver and then went to add more levels. But, along the way, you got confused about terminology used in the new options. I thought we'd clarified that in our email discussion, but I see now I was wrong.

I do not have your non-standard version of C++ string...
So how can I help you with it?

But, there are things wrong on so many levels that I'm not sure what angle to approach. You have fundamental coding issues as well as high-level design issues.

Yes ... that seems a fair evaluation ... but your outdated course and compiler ... the root problem!

You try to define a type nickname for a vector of strings, but you haven't #include'd the vector library.

But ... ANY modern version of C++ has the STL

#include <vector> // this is how to do it in std C++

If you are using any non-standard C++ stuff ... recall you must always first include the definition(s) of any code ... before you try to call it.

David W 131 Practically a Posting Shark

Maybe this will give you some more ideas ...

// beginnerPayProgram.cpp //  // 2014-03-02 //


// Note the added loop, comments, keeping cin stream 'flushed as we go'
// and .. the demo of one simple way for validation, etc...



#include <iostream>
#include <iomanip> // re. setprecision( ), setw( ), etc ...
#include <cctype> // re. toupper ...

using namespace std;


int main()
{
    bool more = true;

    cout << setprecision(2) << fixed; // show 2 decimal places

    while( more ) // top while loop test ... loop until more = false
    {
        cout << "Enter hours worked :  ";
        double hoursWorked;
        if( cin >> hoursWorked )
        {
                cout << "Enter hourly rate  :  ";
                double hourlyRate;
                if( cin >> hourlyRate )
                {
                    cout << "Exempt (Y/N)       :  ";
                    char exempt ;
                    cin >> exempt;

                    exempt = toupper( exempt );
                    if( exempt != 'Y' && exempt != 'N' )
                    {
                        cout << "You did not enter 'Y' or 'N' ... \n";
                        continue; // from top 'while loop test' *NOW*
                    }

                    // Ok ... all good so far ... but good to ...
                    // 'flush' cin stream /  'eat' the '\n' char left,
                    // that IS still there at the end of the cin stream

                    while( cin.get() != '\n' ) ; // exits when eats '\n' char left above

                    // Now ... calculate and report

                    cout << "\nGross wages        =  $" << setw( 8 )
                         << hoursWorked * hourlyRate << endl;

                    if( exempt == 'Y' )
                        cout << "NO TAXES …
David W 131 Practically a Posting Shark

Did you realize that you are taking in your 3 data elements twice?

And that the 2nd 'take in' set of data ... over-write the first?

Also ... do you realize that in math:

For any value a,

( a - 0.18*a ) 
= 
a * (1 - 0.18) 
= 
a * 0.82 

So your calculation can be a little more efficently coded ... yes?

David W 131 Practically a Posting Shark

A quick Google turned up this ... (for starters)

http://www.cprogramming.com/tutorial/function-pointers.html

...

Callback Functions
Another use for function pointers is setting up "listener" or "callback" functions that are invoked when a particular event happens. The function is called, and this notifies your code that something of interest has taken place.

...

You might want to start with function pointers ... like you may wish to use when passing in a different compare function to a library sort ... to sort on different fields, etc... ?

David W 131 Practically a Posting Shark

If this is another problem ...

(i.e. a new assignment you are working on),

please start a new thread, and state clearly what the problem is, what your quide lines are, if any,

(for example: use C strings only? sort a certain type of formated file ? ... etc.),

and show what code you have ... and where you are having problems coding ... or not getting the expected results.

David W 131 Practically a Posting Shark

I do not have access to your string type ... (nor do I care to have access to it.)

I sent you a link to a string class ... so that we can both work 'on the same basis' ... I am willing to help you, if I can ... with that.

It IS really way over-due for you to get updated to the present version of a C++ compiler ... (and several are free !!!)

If you want to use C type (dynamic) strings ... I have a free student C utilities library that easily handles that (with utilities for Cvec and Clist with insert and merge sorts, etc...) :

#include "readLine.h"

/* readLine.h */ /* this version: 2013-07-10 */

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

/*
Safe string data entry from file ... to replace gets and fgets
BUT free new memory ... when done! Don't forget that C strings are
pointers to a block of char, with a '\0' char at the terminal end ...

Call like this:

    char* line = readLine( stdin );

    or ...

    while( (line = readLine( FILEp )) )
    {
        // process line ...
    }
*/



#include "readWord.h"

/* readWord.h */ /* this ver 2013-07-11 */

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

/*
Safe string data entry from file or keyboard ...
BUT ... free new memory when done with it!
Don't forget that C strings are pointers to a block of char,
with a '\0' char at the terminal …
David W 131 Practically a Posting Shark

That is not a map of M -> v ...

v is all set to zero there,

( but it shows the general idea,
if zero is replaced by M[i][j] )

Now show your code for ...

M1*M2 => M3

with row & column checking

and the appropriate size for M3

David W 131 Practically a Posting Shark

Can you show your map of a 'n by m' Matrix to a vector of length n*m ?

And then do regular matrix multipliction ( with appropriate size checks) ...

Then ... M1*M2 => M3

should map to ...

vm1*vm2 => vm3

David W 131 Practically a Posting Shark

Is what you are trying to do is to transform a vector?

i.e. M1*v1 => v2
i.e. Matrix1 times vector1 = vector2 ?

David W 131 Practically a Posting Shark

Check here ...

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

Also see 2 demos there ...

David W 131 Practically a Posting Shark

It seeems you don't have C++ string
Try using the class String I linked to, on your other post.

David W 131 Practically a Posting Shark

You could use the above example (copied now here below):

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

bool more() // defaults to yes (more) ...
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}
David W 131 Practically a Posting Shark

Yes ... but here, you seem to NOT want (or need) any code to handle file input ...

since you are getting input from the keyboard to fill up a test vector of strings to sort, etc.

So ... just use code that does that job ... input test strings into an (initially empty) vector of strings, from the keyboard ... as per user input function example(s).

David W 131 Practically a Posting Shark

Also ... it would be best to accept ONLY valid input from the user ... (if you are NOT using input from a valid data file) ...

You could do that, coding for your user input function, something like below:

bool isAllDigit( const string& s )
{
    for( int i = s.size()-1; i >= 0; -- i )
    {
        if( !isdigit(s[i]) ) return false;
    }
    return true;
}

bool isAllAlpha( const string& s )
{
    for( int i = s.size()-1; i >= 0; -- i )
    {
        if( !isalpha(s[i]) ) return false;
    }
    return true;
}

bool isValid( const string& s )
{
    if( isAllDigit(s) ) return true;
    if( isAllAlpha(s) ) return true;

    size_t pos = s.find_first_of( "0123456789" );
    bool valid = true;
    if( pos == string::npos ) valid = false; // not likely ... just in case
    else if( isAllAlpha( s.substr( 0, pos )) && isAllDigit( s.substr( pos )) )
        return true;
    else valid = false;

    cout << "\nInvalid input ... please try again ...\n";

    return valid;
}

// valid line entry only ...
// 1. a valid int (only one valid int on line)
// 2. a string (no embedded digits 0..9)
// 3. a string (as in 2.) immediately followed by one valid int
void loadFromUser( VecStr& vs )
{
    cout << "Valid input here is:\n"
         << "1. a valid integer (only one valid int on line ... or\n"
         << "2. a string (no embedded digits 0..9) ... or\n"
         << "3. a string (as in 2.) …
David W 131 Practically a Posting Shark

Since you are using C++ ...

Why not just easily USE C++ string ...

Then ...

your program to input strings into a vector of strings ...

and to sort them, as you wish ...
(code and use your own compare function for the sort
... see or use the example compare function used above)

can easily all be done in just ONE short file.

Using the C++ STL ... for vector and sort, etc...
IS THE WAY to go !

Please review the examples and functions provided above.
You really do have all that you need there, using C++ string and the C++ STL ...

David W 131 Practically a Posting Shark

What do you want to have in your main function ...

Maybe ... something like this:

int main()
{
    VecStr vs; // construct empty vector ...

    loadFromUser( vs );

    cout << "Before sorting ... \n";
    print( vs );
    sort( vs.begin(), vs.end(), myCmp );
    cout << "After sorting ... \n";
    print( vs );


    pause( "Press 'Enter' to continue/exit ... " );
}
David W 131 Practically a Posting Shark

These may help ... (edit out the file stuff, also, of course.)

typedef vector< string > VecStr;


char takeInChar( const string& msg )
{
    cout << msg << flush;
    string reply;
    getline( cin, reply );
    if( reply.size() )
        return reply[0];
    // else ...
    return 0;
}
bool more()
{
    if( tolower( takeInChar( "\nMore (y/n) ? " )) == 'n' )
        return false;
    // else ...
    return true;
}

void loadFromUser( VecStr& vs )
{
    do
    {
        string line;
        cout << "Enter next line: " << flush;
        getline( cin, line );
        vs.push_back( line );
    }
    while( more() );
}
David W 131 Practically a Posting Shark

My output, for the test file above, as input, was:
(matches your request ...yes?)

Before sorting ...
1
10
2
9
a1
b10
a10
a2
a9
b1
b2
After sorting ...
1
2
9
10
a1
a2
a9
a10
b1
b2
b10
Press 'Enter' to continue/exit ...
David W 131 Practically a Posting Shark

Try it with this small test 'text file', and name the file to match the file name used in the program ...

"alphaNum.txt"

It is easy (easier sometimes) to test out a program using file data ... that is 'known to be valid data'

1
10
2
9
a1
b10
a10
a2
a9
b1
b2
David W 131 Practically a Posting Shark

If your input data is close to what you show above ...

something like the following could do ...

/* sortAlphaNum.cpp */  /* 2020-02-24 */


/*
Here is what I have to do:

To have numbers sorted properly even when they aren't justified with leading 0's:

1
2
...
9
10
Instead of:

1
10
2
...
9

Also to have numbers sorted properly even if they aren't in the lead of the string:

a1
a2
...
a9
a10
b1
b2
...
Instead of:

a1
a10
a2
...
a9
b1
b10
b2
...
*/


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

#include <algorithm> // sort
#include <cctype>    // re. isdigit

using namespace std;

#define FNAME "alphaNum.txt"

typedef vector< string > VecStr;

bool loadFromFile( VecStr& vs )
{
    ifstream fin( FNAME );
    if( fin )
    {
        string line;
        while( getline(fin, line) )
            vs.push_back( line );
        fin.close();
        return true;
    }
    return false;
}

void print( const VecStr& vs )
{
    for( size_t i = 0; i < vs.size(); ++i ) cout << vs[i] << endl;
}

void pause( const char* msg )
{
    cout << msg << flush;
    while( cin.get()  != '\n' ) ;
}

int toInt( const string& s )
{
    istringstream iss(s);
    int tmp;
    iss >> tmp;
    return tmp;
}

struct Item
{
    string s;
    int val;
} ;

bool myCmp( const string& a, const string& b )
{
    Item a_itm, b_itm;
    istringstream iss_a(a), iss_b(b);
    char c;
    string tmp;

    while( iss_a >> c )
    {
        if( …
David W 131 Practically a Posting Shark

If you were to use stringstream objects, your file conversion from ..

7 regular data 'words' on each line ...

to ...

all 7 sequential words on their own sequential line,
(with the exception that the 2nd and 3rd words are both on the 2nd line, separated by one space) ...
If you were to use stringstream objects, your file conversion from ..

7 regular data 'words' on each line ...

to ...

all 7 sequential words on their own sequential line,

(with the exception that the 2nd and 3rd words are both on the 2nd line, separated by one space) ...

This becomes really easy, (once you see the facility of using stringstream to parse a line) ...
This becomes really easy, (once you see the facility of using stringstream to parse a line) ...

// fileLineToSequenceData.cpp //  // 0213-08-19 //


#include <iostream>
#include <fstream>
#include <sstream> // re. stringstream obj's ...
#include <string>


using namespace std;

const char* FNAME_IN = "inDat.txt";
const char* FNAME_OUT = "outDat.txt";


/*
10BCE0014       Manohar Khanna 4 CSE613 CSE501 CSE613
10BCE0023       Vijay Ahari 4   ENG401  CSE503  CSE401
10BCE0147       Prakhar Dixit   4   CSE503  CSE623  CSE501
11BCE0258       Abdul Kadir 3   ENG301  CSE502  CSE613
11BCE0321       Rahul Garg  3   ENG301  CSE503  CSE501
11BCE0326       Bhavya Jain 3   CSE301  CSE421  CSE512
12BCE0026       Rakesh Kapoor   2   ENG201  CSE302  CSE303
12BCE0265       Sonam Krishna   2   ENG401  CSE512  CSE413
12BCE0413       Vinay Khatri    2   ENG201  CSE301  CSE203
13BCE0002       Karan Lodha 1   ENG102  CSE102  CSE301
13BCE0041       Shyam Gupta 1   ENG101  CSE101  CSE102 …
David W 131 Practically a Posting Shark

Here is a start to some C++ revision of your code ...

#include <iostream>
// #include <conio.h> // avoid as it is not standard so code will not be portable


// take in two integers and return the sum 

void takeInAandBandReturnSum( int& result )
{
    bool ok = false;
    while( !ok )
    {
        int a, b;
        std::cout << "Enter Numbers a and b separated by a space : " << std::flush;
        if( std::cin >> a >> b && std::cin.get() == '\n' )
        {
            result = a + b;
            ok = true;
        }
        else
        {
            std::cin.clear(); // clear cin error flags
            std::cin.sync(); // 'flush' cin stream ...
            std::cout << "\nInvalid data ... try again.\n";
        }
    }
}
David W 131 Practically a Posting Shark

You said you were learning C++ ... but did you realize that your code was in the C style?

In C++, one can pass by reference ... and so will not have to dereference a value passed into a function using the * dereference operator (that is used with passed in pointers that one wants to dereference)

And note that main returns an int

so it is ...
int main() // not void main()

jandanielsaclolo commented: Thanks! +0
David W 131 Practically a Posting Shark

Oops ... just noticed that in the above demo code ... that there should have been

<= (less than or equals)

// returns a non-empty string with a max string length of char's
std::string takeIn( const std::string& msg, size_t maxStrLen )
{
    std::string val;
    for( ; ; ) // loop forever ... until break
    {
        std::cout << msg << std::flush;
        getline( std::cin, val );
        size_t len = val.size();

        if( len && len <= maxStrLen ) // FIXED NOW to also accept maxStrLen chars
            break;

        if( len ) std::cout << "\nOnly " << maxStrLen
                            << " char's allowed here\n";
        else std::cout << "\nBlank line not valid here.\n";
    }

    return val;
}

And another way to code the logic in main ... to avoid using the 'continue' statement to jump out of the switch ...

int main()
{
    cout << "Welcome to 'CAN YOU GUESS MY NUMBER'\n\n";

    int difficulty;
    int pass = 0;
    bool done = false;
    while( !done )
    {
        cout << "Choose your difficulty: \n\n"
             << "1: Easy\n"
             << "2: Normal\n"
             << "3: Hard\n"
             << "0: Quit\n\n"
             << "Enter your choice: 0-3: " << flush;

        cin >> difficulty;

        if( cin.fail() )
        {
            cin.clear(); // in case NON interger was intered value is -1 still
            difficulty = -1;  // set error value to some not used value
        }

        cin.sync(); // 'flush' cin stream

        bool valid = true;
        switch (difficulty)
        {
            case 0:
                if( pass != 0 ) cout << "Thank you for playing.\n\n";
                done = true;
            break;
            case …
David W 131 Practically a Posting Shark

Mary ...

Well learning how to write to file and read back from file, is a basic thing to learn, the OP does not seem to be using any file operations here :)

Note:

a lot of the time, rather then using an if ... elseif ... else structure

or a switch ... case structure

a 'table look up' will do very nicely ... and could save a lot of redundant coding:

#include <iostream>
#include <sstream> // re ostream objects ...
#include <string>


using namespace std;

const size_t MAX_CHARS[] = { 5, 10, 15 };

const string LEVELS[] = { "EASY", "NORMAL", "HARD" };


// returns a non-empty string with a max string length of char's
std::string takeIn( const std::string& msg, size_t maxStrLen )
{
    std::string val;
    for( ; ; ) // loop forever ... until break
    {
        std::cout << msg << std::flush;
        getline( std::cin, val );
        size_t len = val.size();

        if( len && len <= maxStrLen )
            break;

        if( len ) std::cout << "\nOnly " << maxStrLen
                            << " char's allowed here\n";
        else std::cout << "\nBlank line not valid here.\n";
    }

    return val;
}




int main()
{
    cout << "Welcome to 'CAN YOU GUESS MY NUMBER'\n\n";

    int difficulty;
    int pass = 0;
    bool done = false;
    while( !done )
    {
        cout << "Choose your difficulty: \n\n"
             << "1: Easy\n"
             << "2: Normal\n"
             << "3: Hard\n"
             << "0: Quit\n\n"
             << "Enter your choice: 0-3: " << flush;

        cin >> difficulty;

        if( cin.fail() )
        {
            cin.clear(); // in case NON …
David W 131 Practically a Posting Shark

Michael, that was an awesome post!

David W 131 Practically a Posting Shark

Here is a shell that shows one popular student way to start a menu / choice / switch type program.

Note the use of functions to facilitate your logic flow and code developement testing steps.

Note the use of getline for input so that the WHOLE line is input.

#include <iostream>
#include <string>

using namespace std;


void lev1( )
{
    cout << "\n\nLevel 'Easy' is being developed ...\n";
}
void lev2( )
{
    cout << "\n\nLevel 'Normal' is being developed ...\n";
}
void lev3( )
{
    cout << "\n\nLevel 'Hard' is being developed ...\n";
}

int showMenuGetChoice()
{
    cout << "\nWelcome to 'CAN YOU GUESS MY NUMBER?'\n\n"
         << "Choose your difficulty: \n"
         << "1: Easy\n"
         << "2: Normal\n"
         << "3: Hard\n"
         << "0: Quit\n"
         << "Enter your choice 0..3 : " << flush;
    string line;
    getline( cin, line );
    if( line.size( ) != 0 ) return line[0];
    // else ...
    return 0;
}

void pauseForEnter()
{
    cout << "\nPress 'Enter' to continue ... " << flush;
    string line;
    getline( cin, line );
}


int main()
{
    bool done = false;
    do
    {
        switch( showMenuGetChoice() )
        {
            case '1' : lev1(); break;
            case '2' : lev2(); break;
            case '3' : lev3(); break;
            case '0' : done = true; break;
            default: cout << "\n\nYou have made an invalid choice.\n";
        }
    }
    while( !done );

    pauseForEnter();

}