David W 131 Practically a Posting Shark

The example that I mentioned that you would like to see ...

// input1.txt
/*
1 2 3 4 4 5 6 7 7 7 8 9 10 20 25
*/
// input2.txt
/*
1 2 5 5 9 9 10 11 12 13 14 14 15 15 15 16 17 18 19 20 21
*/

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

    if( fin1 >> i1 ) ++ countIn;

    // Now firstly ... handle case of ... if empty file 1 ... //
    if( fin1 ) // i.e. count == 1
    {
        // Then ... 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;
                }
            }
        }
        else
        {
            fout << i1 << ' ';  // Do NOT forget to write this //
            ++countOut;
        }
    }


    // check end conditions ... at most below, one line gets executed ... //
    while( fin1 >> i1 ) { fout << i1 << ' '; ++countIn; ++countOut; }
    while( fin2 >> i2 ) { fout << i2 << ' '; ++countIn; ++countOut; }

    // 'in' and 'out' counts *should* match if all 'in' was 'out' ok ... //
    cout << "countIn = " << countIn << endl;
    cout << "countOut = " << countOut << endl;
}
David W 131 Practically a Posting Shark

Just make a text editor and incorporate the interpreter.

What about the GUI?

( A text editer too ? Recall ... a cool project for just beginners :)

David W 131 Practically a Posting Shark

Hey ... sorry I missed that ... is that why you 'down-voted' ?

It was not me as downvoted you :)

Sorry ...

anyways ... it's good to hear @Gribouillis, Dani's 'Posting Maven' :)

David W 131 Practically a Posting Shark

This, (to me), seems to be a much simpler 'first go' ... and a possibly more efficent re-design ....

(that yields sets of Playoff Players all ready initialed in a random simulation) ...

and thus it may be of interest to you, (and easier for you to understand and re-work?)

Take a look:

// test_classPlayoff.cpp //

#include <iostream>
#include <iomanip>
#include <vector>
#include <cstdlib> // re. rand, srand
#include <ctime>
#include <algorithm> // re. vector sort


using namespace std;

const int PLAYOFF_SIZE = 128;

struct Player
{
    int id;
    int grade; // 1..10
    Player( int grade=0 ) { ++ count; id = count; this->grade = grade; }

    static int count;
};

// ok to set inital value here ... //
int Player::count = 0;

bool myCmp( const Player& a, const Player& b )
{
    return b.grade < a.grade; // re. desending sort .... //
}

ostream& operator << ( ostream& os, const Player& pl )
{
    return os << " id<" << setw(3) << pl.id
              << ">:grade <" << setw(2) << pl.grade << '>';
}



class Playoff
{
public:
    Playoff()
    {
        players.reserve(PLAYOFF_SIZE);
        srand( time(0) );
        for( int i = 0; i < PLAYOFF_SIZE; ++i )
        {
            Player tmp( rand() % 10 + 1 );
            players.push_back( tmp );
        }
        sort( players.begin(), players.end(), myCmp );
    }
    typedef vector< Player >::iterator iter;
    typedef vector< Player >::const_iterator const_iter;

    iter begin() { return players.begin(); }
    iter end() { return players.end(); }

    const_iter begin() const { return players.begin(); }
    const_iter end() const { return players.end(); …
David W 131 Practically a Posting Shark

Just write your own with python like normal programmars do, it the pythonic approach.

Yep ... a really cool 'beginner' project :)

David W 131 Practically a Posting Shark

And then ... perhaps next step ... 'revise code to crash proof input' ... i.e. to accept only valid user input:

# takeInHousePrices.py #

def takeInInt( msg, low, high ):
    while 1:
        try:
            val = int( input( msg ) )
            if val == 0 or low*1000 <= val <= high*1000:
                return val
            else:
                print( 'Prices valid here are those in range {}k..{}k'.\
                       format( low, high ))
        except( ValueError ):
            print( '\nValue Error!  Only integers are valid here!' )

houses = []
while True:
    value = takeInInt( 'Enter price for house #{} (0 to exit): '.format(len(houses)+1), 50, 100 )
    if value:
        houses.append(value)
    else:
        break

if houses:    
    mid = takeInInt( "Enter a 'middle' price: ", 50, 100 )

    print( 'Houses with a price less than or equal to the mid price of {}:'.format(mid) )
    tmpLst = [str(house) for house in houses if house <= mid]
    tmpLst.sort()
    print( '\n'.join(tmpLst) )


    print( 'Houses with a price greater than the mid price of {}:'.format(mid) )
    tmpLst = [str(house) for house in houses if house > mid]
    tmpLst.sort()
    print( '\n'.join(tmpLst) )

    ssum = sum(houses)
    print( 'Total price of {} houses sums to {}'.format(len(houses), ssum) )
    print( 'Average house price for these {} houses was {:.2f}'.format( len(houses), ssum/len(houses)) )
David W 131 Practically a Posting Shark

Dont use file as a variable name,file is a reserved word used bye Python.

Hey ... sorry I missed that ... is that why you 'down-voted' ?

David W 131 Practically a Posting Shark

You may like to see this demo (modify to suit your needs):

import os


def search_linetest():
    path = 'C:/Users/dwzavitz/Desktop/2014Files/DaniPython' #'/Users/jolie_tia/Documents'
    dir = os.listdir(path)
    for file in dir:
        print( file )
        if '.exe' in file:
            pass
        else:
            #open('/Users/jolie_tia/Documents/sample.txt')
            f = open( file )
            s = f.read()
            #x= s.find('I was scared to pieces.')
            x= s.find( 'print' )
            if x != -1:
                print( 'Line was found starting at character', x )
            else:
                print('Line not found')
            input( "Press 'Enter' to continue ... " )


search_linetest()
David W 131 Practically a Posting Shark

Don't forget to handle 'all' the cases ...
including if either of the input files is empty.

This can actually be a little tricky to handle.

You may like, while debugging, to count all the inputs and outputs, to ensure the totals match.

If you would like to see an example, (with debugging code that counts input and output), no problem :)

David W 131 Practically a Posting Shark

Your desired main function (with the merge file function) could look something like this:

int main()
{

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

    if( fin1 && fin2 && fout )
    {
        mergeFiles( fin1, fin2, fout );
        fout.close();
        fin2.close();
        fin1.close();
    }
    else cout << "There was some problem opening files ...\n";
}
David W 131 Practically a Posting Shark

Take a look at this little demo ...

#include <iostream>

// re comparing two arrays to see if hold 'equal' items ... //
#include <vector>
#include <algorithm> // re. vector sort ... //


using namespace std;


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

// passed in arrays must be at least size 'size' ... //
bool equals( const int a[], const int b[], int size )
{
    vector< int > va( a, a+size ); // construct vector copy
    vector< int > vb( b, b+size ); // construct vector copy

    sort( va.begin(), va.end() );
    sort( vb.begin(), vb.end() );

    cout << "'a' sorted = " << va << endl;
    cout << "'b' sorted = " << vb << endl;

    return va == vb;
}

void pause()
{
    cout << "\nPress 'Enter' to continue ... " << flush;
    cin.get();
    cin.sync();
}


int main()
{
    int board[][5] =
    {
        {5,6,18,19,34},
        {5,25,28,29,40},
        {17,24,26,37,43},
        {1,8,14,34,42},
        {19,26,31,32,42},
        {5,14,27,35,40},
        {28,32,33,37,43},
        {2,13,18,41,45},
        {1,4,6,10,41}
    };
    int size = sizeof board / sizeof *board;
    cout << "size = " << size << endl; // 9 //



    // see if beginning row has same items as any other row

    bool redundant = false;
    for( int i = 1; i < size; ++i ) // start with i = 1 ... //
    {
        if( equals( board[0], …
David W 131 Practically a Posting Shark

One 'quick way' that comes to mind ...

// countCharsWords2.cpp //

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

using namespace std; 

// can easily change FNAME here ... //
const string FNAME = "Results.txt";
/*
Hello! Computer Science rocks! :) WOOHOOO!
*/

// can easily adjust char's to be included as PUNC ... here //
const string PUNC = ".?!,;";

void processFile( ifstream& fin )
{
    int numWords = 0, numChars = 0;
    string word;

    cout << fixed << setprecision(0); // show NO decimal

    // input each word until end of file ... //
    while( fin >> word )
    {
        ++numWords;
        int len = word.size();
        if( PUNC.find( word[len-1] ) != string::npos )
            word.erase( len-1 );
        numChars += word.size();
        // show words ...//
        cout << ' ' << left << setw( 15 ) << word;
    }

    cout << "\n\nNumber of words was " << numWords
         << "\nNumber of letters was " << numChars
         << "\nAverage letters per word was "
         << double(numChars) / numWords << endl;
}


int main() 
{ 
    ifstream fin( FNAME.c_str() );
    if( fin )
    {
        processFile( fin );
        fin.close();
    }
    else
        cout << "\nThere was a problem opening file "
             << FNAME << endl;

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

Here is a little demo of using a 'C vector' (Cvec),
(here using ...
a readily expandable dynamic array of dynamic C strings,
to handle a problem of reading in a text file of lines,
using readLine, which is an emulation of C++ getline,
into a dynamic array of dynamic C strings ...
and then showing that vector of dynamic C strings.)

/* read_places.c */

/*

  a little demo of using "CvecOfString.h"
  to read and show file "places.txt"

  http://developers-heaven.net/forum/index.php/topic,2580.msg2865.html#msg2865

*/

/* also uses files "readLine.h" and "Cvec.h"  available at link above */
#include "CvecOfString.h"


const char* FNAME = "places.txt";
/*
Brasil
Portugal
Chile
Espanha
*/

void printCvec( const Cvec* cv )
{
    int i;
    for( i = 0; i < cv->size; ++ i )
    {
        printf( "%s\n", cv->ary[i].str );
    }
}

int main()
{
    FILE* fp = fopen( FNAME, "r" );
    if( fp )
    {
        Cvec cv;
        Rec rc;
        char* line;
        initCvec( &cv );
        while( (line = readLine( fp )) )
        {
            rc.str = line;
            push_backCvec( &cv, &rc );
        }
        fclose( fp );
        printf( "cv.size = %d, cv.cap = %d\n", cv.size, cv.cap );
        printCvec( &cv );

        printf( "\nAfter sorting ... \n" );
        msort( &cv );
        printf( "cv.size = %d, cv.cap = %d\n", cv.size, cv.cap );
        printCvec( &cv );

        printf( "\nAfter clearing ... \n" );
        clearCvec( &cv );

        printf( "cv.size = %d, cv.cap = %d\n", cv.size, cv.cap );
        printCvec( &cv );
    }
    else
        printf( "\nThere was a problem opening file %s\n", FNAME …
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

Do you have examples of output for input of 1 and 2?
(Or is the first valid input 3?)

David W 131 Practically a Posting Shark

If you took what I gave you above as a start ... you might have coded something like the following:

// countCharsWords.cpp //

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

using namespace std; 

// can easily change FNAME here ... //
const string FNAME = "Results.txt";
/*
Hello! Computer Science rocks! :) WOOHOOO!
*/

// can easily adjust char's to be included as PUNC ... here //
const string PUNC = ".?!,;";



int main() 
{ 
    ifstream fin( FNAME.c_str() );
    if( fin )
    {
        int numWords = 0, numChars = 0;
        string word;

        cout << fixed << setprecision(0); // show NO decimal

        // input each word until end of file ... //
        while( fin >> word )
        {
            ++numWords;
            int len = word.size();
            // if last char is in string PUNC ... //
            if( PUNC.find( word[len-1] ) != string::npos )
                word.erase( len-1 );
            numChars += word.size();
            // show words ...//
            cout << ' ' << left << setw( 15 ) << word;
        }
        fin.close();

        cout << "\n\nNumber of words was " << numWords
             << "\nNumber of letters was " << numChars
             << "\nAverage letters per word was "
             << double(numChars) / numWords << endl;
    }
    else
        cout << "\nThere was a problem opening file "
             << FNAME << endl;

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

any suggestions on how to replace the specific character with a different character within the string while running a loop? I am in a no prereq class and am not really connecting with this...

Hint was:

loop, test character code, if one that needs replacing replace it...

Further hint:
you could use some C code something like this:

char test[] = "The cat was fat."; /* recall '\0' terminated */
char* p = test; /* get a pointer to first char */

/* change each small 't' to 'b' ... */
/* loop until reach terminal '\0' char */
while( *p ) 
{ 
    if( *p == 't' ) *p = 'b' ; 
    ++p; 
}

printf( test ); /* The cab was fab. */
David W 131 Practically a Posting Shark

You could make a copy of the series of numbers,
then sort the copies,
and then compare the sorted series to see if the same.

David W 131 Practically a Posting Shark

Why not use C++ string since you are using C++ ...
and something like below ...

ifstream fin( fnameCppStr.c_str() );
if( fin )
{
    int numWords = 0, numChars = 0;
    string word;
    // input each word until end of file ... //
    while( fin >> word )
    {
        ++numWords;
        int len = word.size();
        if( ".?!,;".find( word[len-1] ) != string::npos )
            word.erase( len-1 );
        numChars += word.size();
    }
    fin.close();
    // report counts, etc...

}
else
{
    // print some error message
}

And NOT ...

#include "iostream"
#include "fstream"

Instead use ...

#include <iostream>
#include <fstream>
David W 131 Practically a Posting Shark

'IDLE' is always an easy ...
(and free) way to start coding in Python :)

David W 131 Practically a Posting Shark

You might also like to see this Python 3... example:
(that uses a function to loop until valid integer input)
(and that loops to ask user if more numbers to be input)
(and that demo's the use of a list 'generator')
(and that demo's the use of 'join')

# sumNumbers.py #

def takeInInt( msg ):
    loop = True
    while( loop ):
        try:
            i = int(input(msg))
            loop = False
        except( ValueError ):
            print( "Only integers valid here ... try again ..." )
    return i


nums = []
more = True
while( more ):
    num = takeInInt( "Enter next integer to sum: " )
    nums.append( num )
    more = ( input( "More (y/n) ?" ).upper() != 'N' )

lstNumAsStrsGen = list( str(x) for x in nums )
print( '+'.join(lstNumAsStrsGen), '=', sum(nums) )
David W 131 Practically a Posting Shark

100+100
-100-100
-(100)+(-100)
sqrt(100)

The last line above could be tested / handled by:
if "sqrt(" 
    then if  int  
         then if ")" 
            then process ...


The next to last line could be tested / handled by:
else if "+(" or "-("
  then if int   
       then if ")"    
           then if valid_binary_op
              then if int or (int)
                 then process

The first two lines above both could be handled as:
else if int 
   then if valid_binary_op 
      then if int
         then process ...

else ... data input error, that input format not handled here
David W 131 Practically a Posting Shark

@Akash_Soni

Your reply is true ... in the case where your design actually does call (i.e. the program uses it) the default ctor ... other-wise (sometimes) ... you may not want to code for the default ctor ... i.e. the case where you want your compiler to issue an error if programmer inadvently codes for a call to the default ctor (and your design was to prevent that from happening.)

David W 131 Practically a Posting Shark

You could loop until all input was exhasted putting each next element into the next spot in the array on each loop

and yes ... you can also dynamically allocate memory for your array ... and expand the array if it needs more memory

You might like to see an example of a C vector container

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

David W 131 Practically a Posting Shark

Recursion can be tricky ... especially when you first try it ... so look up lots of examples where recursion is used.

For a popular example, see 'quick sort'

The following (inefficent design) on a related example may give you some ideas on how to get started ...

/* getLastCharRecursive.c */

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

/*
    this efficient demo uses recursive calls ...
    string passed in MUST BE NON-empty
*/
char getLastDig( const char* s )
{
    char c = s[0];
    if( *(s+1) == 0 ) return c;
    getLastDig( s+1 );
}

/* a handy utility for many C student coding problems ... */
char takeInChar( const char* msg )
{
    char chr;
    fputs( msg, stdout ); fflush( stdout );
    chr = getchar();
    if( chr != '\n' )
        while( getchar() != '\n' ) ; /* flush stdin ... */
    return chr;
}


int main()
{
    char buf[1024], c, *p;

    do
    {
        for( ; ; )
        {
            fputs( "Enter several char's: ", stdout );
            fflush( stdout );

            fgets( buf, sizeof(buf) , stdin );
            p = strchr( buf, '\n' );
            if( p ) *p = 0;
            else while( getchar() != '\n' ); /* flush stding */

            printf( "You entered '%s'\n", buf );

            /* ensure something entered before breaking ... */
            if( buf[0] ) break; /* if( buf[0] != 0 ) break; */
            /* else...    */
            printf( "You *must* enter something ... "
                    "try again ...\n");
        }

        c = getLastDig( buf );

        printf( "The last char entered (before 'Enter pressed') "
                "was: '%c'\n", c );
    }
    while( tolower( takeInChar( "More (y/n) ? " )) != 'n' );

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

We can create an array of objects for any class , irrespective of whether it has a default constructor or not

Is the above really true?

Please see ...
http://en.wikipedia.org/wiki/Default_constructor
and note the following example that needs
to have a defined default ctor

/*
If some constructors are defined, but they are all non-default, 
the compiler will not implicitly define a default constructor. 
Hence, a default constructor may not exist for a class.
This is the reason for a typical error which can be demonstrated 
by the following example.
*/
class MyClass 
{
  public:
    MyClass (int y); // a value constructor     

  private:
    int x;
};

MyClass :: MyClass (int y)
{
    x = y;
}

int main()
{
    MyClass object(100);     // value constructor called
    MyClass* pointer;        // do not need to know about any existing ctors
    pointer = new MyClass;   // error: no default constructor    
    return 0;
}
David W 131 Practically a Posting Shark

Also @Avishek_1 ...

Please note that in standard C++ (and C)

it is int main ( NOT void main ) i.e. main returns an int

David W 131 Practically a Posting Shark

@Avishek_1

NOT good to use gets ... NOR to revert to old style C++ and mix up OP using stdio.h when OP was using C++ <iostream>

Also since OP using C++, best to use C++ string.

So ... would recommend something like this instead:

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

using namespace std;



int main()
{
    cout <<"Enter a phrase: ";
    string line;
    getline( cin, line );

    istringstream iss( line ); // construct iss obj. from line

    // now parse and get word count and character count
    int chcount = 0;
    int wdcount = 0;
    string word;
    while( iss >> word )
    {
        ++wdcount;
        chcount += word.size();
    }

    // report ...
    cout << "\nWords = " << wdcount << endl;
    cout << "Characters = " << chcount << endl;

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

This may get you started ...

// function to return true if char c 
// passed in is a vowel ...
// otherwise to return false
bool isVowel( char c )
{
    c = toupper(c);
    if( c == A' || c == 'E' || c == 'I' || 
        c =='O' || c == 'U' )
       return true;
     // else ...
    return false;
}

//int main()
//{
//   prompt for input ...
//   char c = cin.get();
//   if( isVowel( c ) ) cout << c << " is a vowel.";
//   else cout << c << " is NOT a vowel.";
//}
David W 131 Practically a Posting Shark

ok ...

could try (to start) something like...

fileName = "david_w.txt"

#intLevelNum intSecsLeft short text info re player
1            120         newbie 
1            30  
2            120
2            30
2            120
2            60
3            120
David W 131 Practically a Posting Shark

The computer will select a secret number with five different (unique) digits. The object of the game is to guess that secret number. Each guess is answered by the number of digits in the guess number that match or occur in the secret number. You will also be told how many of the digits are in the correct position in the secret number. Through a process of elimination, you should be able to deduce the correct digits using logic.

For example:

If the secret number is "12359"
- you enter "11359"
The computer will report "Number Correct = 4" 
and "Correct Position = 4"
- you enter "55555"
The computer will report "Number Correct = 1" 
and "Correct Position = 1"

I want to create a save file for a game im creating in C++ problem

What data do you wish to save?
Can you give an example of how your data file might look?

David W 131 Practically a Posting Shark

One big thing that is very practical:

Collecting and Analyzing Data

Note that 'Process Control' depends on the above.

David W 131 Practically a Posting Shark

Just remembered this ...

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

some C++ code of 'random generation of 4 letter words' ...

and related student correspondence ...

that you may also like to see for ideas.

David W 131 Practically a Posting Shark

Since you are using C++, you can use an array of C++ string to hold your words.

This may help get you started ...

const int MAX_NUM_WORDS = 1000; // make big enough 

// ...

// int main()

string words[MAX_NUM_WORDS];
istream fin( "nameOfYourFileOfWords.txt" );
int n = 0;
if( fin )
{
   string word;
   while( n < MAX_NUM_WORDS && fin >> word )
   {
      words[n] = word;
      ++n;
   }
   fin.close();
}
// if file opened ok ... now your array is filled ok
// and has n words in it ... where n is an int with 
// a possible value of 0 to MAX_NUM_WORDS

or ... without using a file ...

string word;
int n = 0;
// prompt here for input ...
while( n < MAX_NUM_WORDS && cin >> word )
{
  words[n] = word;
  ++n;
  // prompt here for input ...
}
David W 131 Practically a Posting Shark

Hey ... we all needed to start, somewhere ... and if some code compiles ... and IF it also gives the 'correct' output ... and if one is just beginning ... that can feel like it IS such a big success ... at first ...

I recall that it DID take me a long time before I wasn't terrorized by compiler errors and warnings ... and actually learned to 'like them' ... as I began to 'see' how they prompted me to fix the typos and other coding errors.

David W 131 Practically a Posting Shark

Some ideas re. new function calls (slight revisions)

#include <iostream>
#include <string>

#include <cstring> // re. strlen, strchr
#include <cctype> // re. toupper..

const char VALID_CHARS[] = "DMU";

const int BUF_SIZE = 1024;

void my_swap( char* s, int i, int j );


// passed in string is ALREADY validated to contain a '#' char at END

// sorts ONLY up to the '#' char at the end ...
// i.e. '#' is left in the end position
void bubble_sort( char* s )
{
    bool swap;
    int size = strlen(s) - 1;
    do
    {
        swap = false;
        for( int d = 1; d < size ; ++d )

        /// ...
}

// no need to check the last char, which we already know is a '#' char
// by the time we call this function ...
bool isValid( const char* s, const char* validChars )
{
    for( size_t i = 0; i < strlen(s) - 1; ++ i )
    {
        if( !strchr(validChars, toupper(s[i])) )
            return false;
    }
    // if reach here ...
    return true;
}


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

McD's is a local abbreviation for McDonalds

As a first step in your conversion to using a C string (array of char's with a terminal '\0' char) ...
you could take in ... using the C++ string ...
then ... at some point ... call cppStr.c_str() to convert to a const C string (i.e copy over to a buffer) ...

David W 131 Practically a Posting Shark

Hey ... it's 4:53 here now ... also

I was just going to leave McD's wi-fi when some over-drunk kids crashed on to my table ... and I noticed you were still working :)

David W 131 Practically a Posting Shark

Try this ...

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

using namespace std;

const string VALID_CHARS = "DMU";


void my_swap( string& s, int i, int j )
{
    char tmp = s[i];
    s[i] = s[j];
    s[j] = tmp;
}

// passed in string is ALREADY validated to contain a '#' char at END

// sorts ONLY up to the '#' char at the end ...
// i.e. '#' is left in the end position
void bubble_sort( string& s )
{
    bool swap;
    int size = s.size() -1 ; // leave end '#' in place ...
    do
    {
        swap = false;
        for( int d = 1; d < size ; ++d )
        {
            if( s[d-1] > s[d] ) // For decreasing order use < //
            {
                my_swap( s, d-1, d );
                swap = true;
            }
        }
        --size;
    }
    while( swap );
}

// no need to check the last char, which we already know is a '#' char
// by the time we call this function ...
bool isValid( const string& s, const string& validChars )
{
    for( size_t i = 0; i < s.size()-1; ++ i )
    {
        if( validChars.find( toupper(s[i]) ) == string::npos )
            return false;
    }
    // if reach here ...
    return true;
}


int main()
{
    string str;
    for( ; ; ) // loop forver until break ...
    {
        cout << "Enter a string to be sorted "
             << "up to the '#' char position in the string: \n";

        getline( cin, str );


        size_t …
David W 131 Practically a Posting Shark

So ... are you saying that #uumdudmm#sfgvdfgsdf
is valid input ?

Or ... only that #uumdudmm# is to accepted ?

in which (2nd) case is the output to be

ddmmmuuu

?

Please provide examples of ALL valid input
And the corresponding expected output

David W 131 Practically a Posting Shark

Isn't that what the 2nd example on the above page does?
(Did you see it there?
I added it later than the first edit.)

David W 131 Practically a Posting Shark

Are you saying the input can be

EITHER

1) "with # at the end" // only dmu are valid here

or

2) "up to #" ... ignore rest // only dmu valid upto #

?

David W 131 Practically a Posting Shark

Try this ... (to get started) ...

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

using namespace std;

const string VALID_CHARS = "DMU";


void my_swap( char& a, char& b )
{
    char tmp = a;
    a = b;
    b = tmp;
}

// passed in string is validated to already contain '#' ....
void bubble_sort( string& s )
{
    bool swap;
    size_t size = s.find( '#' );
    do
    {
        swap = false;
        for( size_t d = 1; d < size; ++d )
        {
            if( s[d-1] > s[d] ) // For decreasing order use < //
            {
                my_swap( s[d-1], s[d] );
                swap = true;
            }
        }
        --size;
    }
    while( swap );
}


bool isValid( const string& s, size_t size, const string& validChars )
{
    for( size_t i = 0; i < size; ++ i )
    {
        if( validChars.find( toupper(s[i]) ) == string::npos )
            return false;
    }
    // if reach here ...
    return true;
}


int main()
{
    string str;
    for( ; ; ) // loop forver until break ...
    {
        cout << "Enter a string to be sorted "
             << "up to the '#' char position in the string: \n";

        getline( cin, str );


        size_t i = str.find( '#' );
        if( i != string::npos )
        {
            if( isValid( str, i, VALID_CHARS ) ) break;
            // else ...
            cout << "Only " << VALID_CHARS
                 << " are valid here ... \n";
        }

        // else ... if reach here ...
        cout << "\nYour string needs to have a '#' char in …
David W 131 Practically a Posting Shark

If you only accept ... U, M, and D

Then you should validate your input to only accept that ...

or if lower case ... to change lower umd to UPPER UMD

at the input stage ... including validating that the string ENDS witha # (or has a # somewhere ... if it is also permitted to NOT be at the end)

Then ... pass that validated string to the sort function
and output ONLY the sorted char's up to the # char

project requires on letters of U, M, and D and say you put 'em in MDDMU#, it will be UMMDD. thats how its supposed to be. and without # at end like my original code.

David W 131 Practically a Posting Shark

Since using C++, why not use C++ string and gain the ease of its use ?

Try something like this:

#include <iostream>
#include <string>

using namespace std;


void my_swap( char& a, char& b )
{
    char tmp = a;
    a = b;
    b = tmp;
}

// passed in string is validated to already contain '#' ....
void bubble_sort( string& s )
{
    bool swap;
    size_t size = s.find( '#' );
    do
    {
        swap = false;
        for( size_t d = 1; d < size; ++d )
        {
            if( s[d-1] > s[d] ) // For decreasing order use < //
            {
                my_swap( s[d-1], s[d] );
                swap = true;
            }
        }
        --size;
    }
    while( swap );
}



int main()
{
    string str;
    for( ; ; ) // loop forver until break ...
    {
        cout << "Enter a string to be sorted "
             << "up to the '#' char position in the string: \n";

        getline( cin, str );


        size_t i = str.find( '#' );
        if( i != string::npos ) break;

        // if reach here ...
        cout << "\nYour string needs to have a '#' char in it ... \n";
    }


    bubble_sort(str);

    cout << "Here is 'str' sorted up to '#' ...\n";
    cout << str << endl;

    cout << "\nPress 'Enter' to continue/exit ... " << flush;
    string dummy;
    getline( cin, dummy );
    return 0;
}
catastrophe2 commented: great code, but its a bit far from what i need. this code sorts almost any string, which is great! but it sorts it in alphabet i noticed and includes # at end of sort, which cant be there. more below... +1
David W 131 Practically a Posting Shark

Maybe ... they just have not yet learned about C++ "const correctness" ?

The use of const seems to be left ... till later ... for many students :)

David W 131 Practically a Posting Shark

'const' ...
in your examples ...

tells the compiler that the values in the array are NOT to be changed ... and the compiler will warn you then, if you / your program ... later ... tries to change any values in the array ...

Try compiling some code, that -> inside a function that has a const array passed in ... then attempts to change the values in the array ... and then SEE what your compiler reports back.

David W 131 Practically a Posting Shark

In case you have not yet encountered using the C++ STL vector container, (which is really just an easily re-usable and easily expandable dynamic array), you might like to see this demo ... that just uses an array with the max size pre-fixed at compile time ...

Note the little 'trick' of using/setting the first element value in the array to the min and max values, to get started ...

and then, to begin traversing the values, testing if lesser ... or greater ... for the rest of the array elements ... if any exist.

// aryStructSalesLowHigh.cpp //

// demo ...
// take in an array of struct ...
// and then find low and high values ...
// and output processed results

// note:
// we start by setting first element (if exists) in array to
// lowest and highest ...
// then change from there ... (while more elements exist)


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

#include <iostream>
#include <sstream> // re. stringstream objects ...
#include <string>
#include <cctype> // re. tolower ...

using namespace std;

const int TEAM_SIZE = 5;
const int BONUS = 1000;

struct Sales
{
    string name;
    int dollars;

    // ctor with default values ...
    Sales( const string& n="", int d=0 ) : name(n), dollars(d) {}
} ;

// def'n of overloaded operator << for Sales objects ...
ostream& operator << ( ostream& os, const Sales& s )
{
    return os << s.name <<", $" << s.dollars;
}

// some utility functions to ease program …
David W 131 Practically a Posting Shark
David W 131 Practically a Posting Shark

@naveen1993

Please note:

  1. old post (now dead? - maybe you missed the date?)

  2. NOT portable code ...
    if one uses <conio.h> , clrscr, getch, etc...

  3. maybe you missed the CLEAR warning of @Ancient Dragon
    about NOT using gets!!!

    Please Google ... "C why DO NOT use gets"

  4. Your indent style is needing big improvement.