Thread: Second Program

  1. #1
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124

    Second Program

    Hey there everyone

    I've been reading posts on this forum for quite a while and really think that it rules.

    Anyway I've been learning C++ on and off from sources on sites for the month. Today I purchased "C++ From the Ground Up" by Herbert Schildt and will work through it hopefully expanding my knowledge. I also have absolutely no previous background with regards to programming except for a little bit of Delphi (which I hated).

    The main reason for this post is to get some comments on this little program thing I made. I'd just like to hear what people have to say and stuff, and if there are any tips or things regarding C++ that people would like to share. I'm really dedicated and want to learn this language well. I have years...

    Here is the code:

    Code:
    // THE GUESSING GAME by CC
    // This is a simple game that will randomly
    // pick a number that the user must try to
    // guess. The user gets 5 tries. My second
    // program actually. 
    // Last updated: 21/11/2003
    //
    // Changes:
    //          Added score system
    //          Code cleanups
    //          Added 'tries'
    
    #include <string.h>
    #include <time.h>
    #include <stdlib.h>
    #include <iostream> 
    using namespace std;
    
    // Global variables for RNG
    const int LOW = 0;
    const int HIGH = 100; 
    
    
    int main()
    {   
        char again ('y');
        int x, y, limit, count, final;
        
        ////////// RANDOM NUMBER GENERATOR ///////////
        // Declare variable to hold seconds on clock.
        time_t seconds;
        // Get value from system clock and place in seconds variable.
        time(&seconds);
        // Convert seconds to a unsigned integer.
        srand((unsigned int) seconds);
        //////////////////////////////////////////////
    
        int score = 0; // Starting value of user's score
        int tries = 0; // How many times user has played
        
        // The main loop   
        while(again == 'y')
        {    
            system ("cls");
            cout << ":: THE GUESSING GAME ::"<< endl;
            cout << "I'm going to think of a number and you must try to guess it." << endl;
            cout << "You have five guesses. Don't worry, I'll give you a hint if you go wrong." << endl << endl;
            cout << "The number is between 0 and 100. Ready? Let's go...";
            cout << endl << endl << "|| Your score is: " << score << endl;
            cout << "|| Tries: " << tries << endl << endl;
            
            // Randomise the variable each time
            // Part of the random number generator
            x = rand() % (HIGH - LOW + 1) + LOW;
    
            // Giving variables a value
            count = 1; // Just used to number the guesses
            limit = 0;
    
            while(y!=x && limit<5) // loop when y not = x and limit less than 5 
            {
                    cout << count << ". Enter your guess: "; cin >> y;
                    
                    if(y>x)
                    {
                                    cout << "The number: " << y << " is TOO HIGH!" << endl << endl;
                    }
                    
                    else if (y<x)
                    {
                                    cout << "The number: " << y << " is TOO LOW!" << endl << endl;
                    }
            count++;
            limit++;
            } 
            
            if(y==x)
            {
                    cout << endl << "Congrads! You guessed the number.";
                    score++;
            }
            
            else
            {
                    cout << "Sorry, you didn't get it." << endl;
                    cout << "The number was: " << x;
                    score--;
                    // Keeping score always positive or equal
                    if(score<0)
                    {
                                    score=0;
                    }
            }
    
            cout << endl << endl << endl << "Would you like to play again? [y/n]" << endl; 
            cin >> again;
            tries++;
        }     
        return 0;
    }

  2. #2
    Registered User
    Join Date
    Nov 2003
    Posts
    161
    Let all the tips come. I also would like to hear others tips. Here are some of my tips to share;

    for creating games make a compatible dc with the dc that you are going to use to display the image. Then draw on your offscreen dc and use bitblt to copy everything to the other dc that way there is no flickering and drawing on an offscreen dc is faster then a dc that is being displayed.

    pointers are usefull for keeping track of things. You can use an array of char pointers because they are only one byte to keep track of anything. Less memory usage then storing a variable of where things are e.g. to keep track of the end of lines in a string.

    create functions that do simple tasks and from those functions you can create functions that do more advanced tasks. Doing this will make your code look neater if you are going to do procedures multiple of times. Its a way of orgonizing things for you code.

    This tip is good for newbie programmers. When I was a newbie programmer I didn't indent. It was hard reading my code and keeping track of all the if statments and closing brackets. Indent so if you have an unexpected endof file error then it would be easier to find the location of the problem if everything is indented.

    Keep all array's in order from least to highest or vise versa whenever possible this makes it faster to search for something. If you gave us 7 chances to gues your number it will be imposible to get it wrong if you do a binary search. Because 2^7=128.

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    1) why mix old headers and new headers. use ctime not ime.h cstdlib not stdlib.h etc.

    2) char again('y') is poor form. use assignment char again = 'y';

    3) seconds is unused and so a waste. srand(static_cast<unsigned int>(time(0))); just as good.

    4) cast as above and not as (unsigned int). mine is c++ yours is c

    5) only a main function.? main should be kept light. use more functions to do the work. One function,one job.

    Otherwise pretty good.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > C++ From the Ground Up
    This author has too much red ink for my liking
    http://www.accu.org./bookreviews/pub...p/cp001728.htm
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    pointers are usefull for keeping track of things. You can use an array of char pointers because they are only one byte to keep track of anything.
    Are you saying that a a char pointer is 1 byte long?

    To my mind, it is better to put spaces between operators and operands. Just like a == b and not a==b. But it is my opinion...

    Your comments are pretty useless for some of them.
    Code:
    while(y!=x && limit<5) // loop when y not = x and limit less than 5
    Well, the code is self-sufficient. ^^

    I think C++ or C-style casts are for most of them just a matter of taste. I use C-style casts a whole lot because they are shorter and more readable to me.

    Probably a matter of taste again but I like to put all variables at the top of the current scope when it is possible.

  6. #6
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    for creating games make a compatible dc with the dc that you are going to use to display the image. Then draw on your offscreen dc and use bitblt to copy everything to the other dc that way there is no flickering and drawing on an offscreen dc is faster then a dc that is being displayed.
    Don't confuse him, it's his second program!

    I've recently seen a few good examples where someone didn't understand why his program didn't work. He used C-style casts. Had he used C++-style casts, he would have found out quickly.

    Code:
    count = 1; // Just used to number the guesses
    This variable is useless. limit is always one less, so you can just use (limit + 1) instead when you number the guesses.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  7. #7
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124
    Wow! See now this is what a community is for. Sure, I may be new, but just from reading your replies I have learnt quite a bit of things. Thanks to all of you.

    I'll go through each and everyone's comments on my little program and change my code to suit it.

    > C++ From the Ground Up
    This author has too much red ink for my liking
    http://www.accu.org./bookreviews/pu...cp/cp001728.htm
    That was a review of the first edition. I'm working through the third edition and I have only found one error in the code. I'm only in chapter 4 but it's going over stuff that I know.

    I have two more questions. Does anyone have any excerises/questions/quizzes or anything else that I can play with? It's just for practise. When I feel ready I'll take a look at a project in SourceForge and see if I understand what's happening there. I think that's the best way to learn.

    Is the Bloodshed compiler good or should I use the (apparently) popular Borland?

    Thanks again for all the comments!

    Last edited by cyberCLoWn; 12-07-2003 at 06:06 AM.

  8. #8
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124
    Changed a few things according to the suggestions. Is this better?

    Code:
    // THE GUESSING GAME by CC
    // This is a simple game that will randomly
    // pick a number that the user must try to
    // guess. The user gets 5 tries. My second
    // program actually. 
    // Last updated: 07/12/2003
    //
    // Changes:
    //          Added score system
    //          Code cleanups
    //          Added 'tries'
    //          Changes suggested by CBoard
    //              -Use new header files
    //              -Remove int Count
    //              -Changed RNG a bit
    //          Rearranged variables
    
    #include <string.h>
    #include <ctime>
    #include <cstdlib>
    #include <iostream> 
    using namespace std;
    
    // Global variables for RNG
    const int LOW = 0;
    const int HIGH = 100; 
    
    
    int main()
    {   
        char again = 'y';
        int x, y, limit, final;
        int score = 0; // Starting value of user's score
        int tries = 0; // How many times user has played
        
        ////////// RANDOM NUMBER GENERATOR ///////////
        srand(static_cast<unsigned int>(time(0))); 
        //////////////////////////////////////////////
        
        // The main loop   
        while (again == 'y')
        {    
            system ("cls");
            cout << ":: THE GUESSING GAME ::"<< endl;
            cout << "I'm going to think of a number and you must try to guess it." << endl;
            cout << "You have five guesses. Don't worry, I'll give you a hint if you go wrong." << endl << endl;
            cout << "The number is between 0 and 100. Ready? Let's go...";
            cout << endl << endl << "|| Your score is: " << score << endl;
            cout << "|| Tries: " << tries << endl << endl;
            
            // Randomise the variable each time - RNG
            x = rand() % (HIGH - LOW + 1) + LOW;
    
            // Giving variables a value
            limit = 0;
    
            while((y != x) && (limit < 5)) 
            {
                    cout << limit + 1 << ". Enter your guess: "; cin >> y;
                    
                    if(y > x)
                    {
                                    cout << "The number: " << y << " is TOO HIGH!" << endl << endl;
                    }
                    
                    else if (y < x)
                    {
                                    cout << "The number: " << y << " is TOO LOW!" << endl << endl;
                    }
            limit++;
            } 
            
            if(y == x)
            {
                    cout << endl << "Congrads! You guessed the number.";
                    score++;
            }
            
            else
            {
                    cout << "Sorry, you didn't get it." << endl;
                    cout << "The number was: " << x;
                    score--;
                    // Keeping score always positive or equal
                    if(score < 0)
                    {
                                    score = 0;
                    }
            }
    
            cout << endl << endl << endl << "Would you like to play again? [y/n]" << endl; 
            cin >> again;
            tries++;
        }     
        return 0;
    }
    5) only a main function.? main should be kept light. use more functions to do the work. One function,one job.
    I tried taking things into their own functions, but this just made everything so much more complicated. Is it really that important to sue different functions for each seperate job when it's such a simple program?

  9. #9
    Registered User
    Join Date
    Nov 2003
    Posts
    161
    Its not that important if you create something simple. But if you go create something more advanced then you would put lots of functions to do simple tasks and out of those simple functions you would make functions that do more advanced tasks. This way everything is kept light. I also thought it was complicated too when there is a bunch of functions doing simple tasks and then there are other functions made from those functions. Sometimes it gets annoying chasing after the functions to find out what they do so it is alway's a good thing to comment your work If you right click on click on "definition" when the cursor is under the word it will jump to the place where something is declared. This makes it be easier to hunt for the functions.

    You don't have to create many functions if you don't want. Doing this makes every function look more light. If you take a look at the source code of some advanced programs like CodeMax you will see that it has many functions doing simple tasks and then there are functions dervived from those functions.

  10. #10
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    I've recently seen a few good examples where someone didn't understand why his program didn't work. He used C-style casts. Had he used C++-style casts, he would have found out quickly.
    I only use dynamic_cast, otherwise it is C-casts. But could you show me your example? Besides I'm used to it so... ^^

    CC > Well, you could use a do...while loop instead of a while loop I think.

  11. #11
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124
    I thought of a Do While loop this afternoon actually. The thing is, the program works well and does what I want it to do. I could also use For loops if I wanted. It just makes more sense to me with While loops in this particular program. Shouldn't that be enough?

  12. #12
    Amateur
    Join Date
    Sep 2003
    Posts
    228
    I just thought a do...while one would be more appropriate as you want your code to run WHILE the user keep saying yes but you don't ask him the first time.

  13. #13
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    The example involved experiments with Managed C++, so I don't think it's appropriate here.
    But it was discussed here:
    http://www.vbforums.com/showthread.p...hreadid=270084


    cyberclown:
    #include <string.h>
    should be
    #include <cstring>
    too.
    Or remove it completly, you're not using anything from it.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  14. #14
    Registered User cyberCLoWn's Avatar
    Join Date
    Dec 2003
    Location
    South Africa
    Posts
    124
    #include <string.h>
    should be
    #include <cstring>
    too.
    Or remove it completly, you're not using anything from it.
    Mistake on my part. I originally had an array that would hold the player's name, but it irritated me and I forgot to remove the header.

  15. #15
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Changed a few things according to the suggestions. Is this better?
    A few minor nitpicks:

    >system ("cls");
    The system function should be avoided wherever possible. First is the portability issue (system is portable, but the argument cannot be), then there is the speed issue (system is very slow). Most of the time people clear the screen when they really don't need to.

    >endl
    You overuse endl. A better way would be to use '\n' directly in your output strings and then use endl when you need the user to see the output as it flushes the buffer too.

    >x = rand() % (HIGH - LOW + 1) + LOW;
    Beware using modulus with rand, it may not always work well. See also this.

    >while((y != x) && (limit < 5))
    y is uninitialized at this point, your program cannot be guaranteed to do anything rational, much less work correctly. Also, you have several variables that could be declared in a more restrictive scope. For example, limit could be declared within the outer loop.
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue with program that's calling a function and has a loop
    By tigerfansince84 in forum C++ Programming
    Replies: 9
    Last Post: 11-12-2008, 01:38 PM
  2. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  3. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 10:04 PM