David W 131 Practically a Posting Shark

1.

If you know the range of values in the integer matrix 'm', say the values range form 10 to 1009
then you could create an array to hold the counts for each value

// initial all values to 0
int freq[1000] = {0};

//then you could run though the matrix
//and ...
++ freq[ m[i][j]-10 ];

/*

for each i, j in the nested inner loop

then skipping on 0 values in the freq array

just report the freq each value (index goes from 0, 999 but values are (index +10) )

*/

2.
Another way would be to use a struct that holds the value and the freq of that value
and a vector to hold the structs

the first time a values occurs (that is, that value is not already in the vector of struct)
push_back a struct with that value and the count = 1

every time an element in the matrix is aleady in the vector of struct, just ++ the count

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

You seem to be experiencing a very common 'beginner design problem' ... due to a lack of understanding about how cin (stream input) works ... especially when numeric input is expected ... and what then happens when cin enters a 'failed' state.

cin skips over all leading ws (white space) char's and tests the first non-ws char to see if it is of the type expected.

For example:

If an int (type) was being expected, and the 1st non-ws char is a + or - sign or a digit in the range 0..9 ... all is still ok ... and cin will keep taking in valid digits, from the cin stream, until it reaches a non-valid-digit-including-a-ws ( ws includes ' ', '\t', '\n' )

If the integer taken in was within the size limits for an int, no error flags are set ... all is 'good'

Other-wise ... a cin error flag is set and cin enters into a 'failed state' ... and stays in that failed state and will not accept any more input until 'cleared' via cin.clear() ... so any char's that were entered after the failed char and before the 'Enter' key was pressed will still be there in the cin stream

This following little demo may give you some more ideas about ways to deal with cin (single number) input.

// cinErrorDemo.cpp //

#include <iostream>


using namespace std;


char getCharReply( const std::string& msg )
{
    std::cout << msg << std::flush;
    std::string reply;
    getline( std::cin, reply …
David W 131 Practically a Posting Shark

To see some next steps to ...

  1. replacing C++ string with dynamic C strings

  2. replacing C++ STL vector with dynamic array

  3. replacing C++ cout with C printf

you could check here ...

Using C code with C++

David W 131 Practically a Posting Shark

Actually the C coding standard often used does not allow declaring variables inside a 'for loop' ...

So, in C, you could code like this:

/* 
   This is an example of a function that you could call to print out a matrix 
   Note that here, ROWS and COLS are presummed to be GLOBAL CONSTANTS
   in C you would use (for example) ...
   #define ROWS 3
   #define COLS 4
   Note: ROWS and COLS must be 'defined' in your program BEFORE being called in your program
*/

void printMatrix( int matrix[ROWS][COLS] )
{
   int i;
   for( i = 0; i < ROWS; ++ i )
   {
      int j;
      for( j = 0; j < COLS; ++ j )
      {
         printf( "%d ", matrix[i][j] );
      }
      putchar( '\n' ); /* print a new line ... */
   }
}
David W 131 Practically a Posting Shark

Ok ... thanks ... that's good to hear and know :)

And ... sorry ... for jumping too quickly to conclusion.

And ... thanks to poster ... for filling in the code missing ...

Looks like my late edit didn't show any code posted ... just a ':'

David W 131 Practically a Posting Shark

Hey

"DarkLightning7
Junior Poster " ,

I am really new here ... could someone please explain what happened ... that my example code was deleted and hi-jacked?

Is this the way things are supposed to work here?

David W 131 Practically a Posting Shark

Nesting a loop inside another loop is very common.

Suppose you have a matrix of integers.

Suppose the matrix has 3 rows and 4 integers in each row ...

Now if you wanted to print out that matrix, a common C, simple way, would be to code like this:

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();

}
David W 131 Practically a Posting Shark

Yoo might like to see a C++ way of coding ...

Then, if really need dynamic C strings and a dynamic array, you will have a working proto-type to start.

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


//using namespace std;

class Player
{
    std::string name;
    int id;
public:
    // default and value ctor...
    Player( std::string n = "", int i = 0 ) : name(n), id(i) {}
    void print() const
    {
        std::cout << "Name: " << name << ", ID: " << id;
    }
} ;


class Team
{
    std::vector< Player > players;
    std::string tName;
public:
    // default ctor ...
    Team() {}

    void set_tName( std::string tN ) { tName = tN; }

    void push_back( const Player& pl )
    {
        players.push_back( pl );
    }

    void print() const
    {
        for( size_t i = 0; i < players.size(); ++ i )
        {
            players[i].print();
            std:: cout << "\n";
        }
        std::cout << "Team \"" << tName << "\" has "
                  << players.size() << " players.\n";
    }
} ;
David W 131 Practically a Posting Shark

A new link C students may like to have (that's had over 17,000 visits in the first 25 days):

C SOME UTILITY functions ...

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

David W 131 Practically a Posting Shark

Great post Labdabeta