Thread: Fairly simple classes help please

  1. #1
    Registered User
    Join Date
    Nov 2004
    Posts
    13

    Fairly simple classes help please

    Hi all, how's it going?
    I'm a C++ novice and have this bad habit of writing code in one big 'main' file and then trying to split it up into classes and functions afterwards. The following program works fully but I need to have 'Town' as a class that stores the name, poulation and area (a town.h file). I know only the very basics about classes and so don't really know where to start (constructors/destructors etc - not sure how to implement for my code).
    I'd appreciate any help
    thanks
    Sam


    Code:
    #include <iostream>
    #include <conio.h>
    #include <stdio.h>
    #include <string>
    
    //#include "town.h"
    
    using namespace std;
    
    int main()
    {
        int c,g;
        int n = 0;
        
        cout << "How many towns would you like to enter? ";
        cin >> c;
        
        string *narray = new string[c];
        double *parray = new double[c];
        double *aarray = new double[c];
        
        while (n <= (c-1))
        {
            cout << "\nPlease enter the name of town " << (n+1) << ": ";
            cin >> narray[n];
            cout << "Please enter the population: ";
            cin >> parray[n];
            cout << "Please enter the area (km): ";
            cin >> aarray[n];
            cout << narray[n] << " has a population of " << parray[n]
                    << " and an area of " << aarray[n] << "km" << endl;
            n++;
        }
        
        n = 0;
        g = 0;
        
        while (g < c)
        {
            g++;
            if (parray[n] < parray[g])
            {
                n = g;
            }
        }
        
        cout << "\n" << narray[n] << " has the largest population" << endl;
        
        
        n = 0;
        g = 0;
        
        while (g < c)
        {
            g++;
            if (aarray[n] < aarray[g])
            {
                n = g;
            }
        }
        
        cout << narray[n] << " has the largest area" << endl;
        
        
        n = 0;
        g = 0;
        
        while (g < c)
        {
            g++;
            if ((aarray[n]/parray[n]) < (aarray[g]/parray[g]))
            {
                n = g;
            }
        }
        
        cout << narray[n] << " has the largest population density" << endl;
        
        
        delete[] narray;
        delete[] parray;
        delete[] aarray;
        
        getch();
        return 0;
    }

  2. #2
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    You're an idiot oops wrong person.
    anyways sorry for the lame joke but you would write a town class just as you said with a name, population, area.
    You could do something like this.
    Code:
    #include <iostream>
    #include <string>
    
    class town
    {
      public:
      std::string name;
      unsigned int population;
      unsigned int area;
    };
    
    int main(void)
    {
      int numOfTowns;
      std::cin>>numOfTowns;
      town *towns = new town[numOfTowns];
      for(int i = 0; i < numOfTowns; i++)
      {
        //do the prompt thing
        std::cin>>towns[i].name;
        std::cin>>towns[i].population;
        std::cin>>towns[i].area;
      }
      for(int i = 0; i < numOfTowns; i++)
      {
        std::cout<<towns[i].name;
        std::cout<<towns[i].population;
        std::cout<<towns[i].area;
      }
      std::cin.get();
    }
    Last edited by prog-bman; 11-30-2004 at 07:29 PM.
    Woop?

  3. #3
    meow nbk's Avatar
    Join Date
    Jul 2004
    Posts
    45
    Constructors initialize variables at the creation of the class.

    for instance:

    Code:
    class town
    {
        public:
            int population;
            town(int populationI);
    };    
    
    town::town(int populationI)
    {
        population = populationI;
    }
    
    // The call
    
    town myTown(6) ; //Would create a town with 6 people
    That is an example of a constructor(which you really don't need with a simplistic class).

    Private versus Public

    You could choose to make your member variables private, instead of public. You can do it just as you declare the variable public --- private: You then need an accessor function to access the variable(the regular town.population will not work) - you can define the funtion the same way as you defined the constructor.


    Header set-up

    For the header set-up, you should have two files - one for the definitions, one for the declaration.

    The header/cpp file would look something like this:

    Code:
    /*********town.h*********/
    #ifndef TOWN_H
    #define TOWN_H
    
    class town
    {
        public:
            town(int populationI);
        private:
            int population;
    };    
    
    #endif
    
    
    /*********town.cpp*********/
    
    town::town(int populationI)
    {
         population = populationI;
    }
    
    /*********main.cpp*********/
    
    include <iostream>
    
    int main()
    {
        town myTown(5);
    }
    Ask any questions you want
    Last edited by nbk; 11-30-2004 at 05:13 PM.

  4. #4
    Registered User
    Join Date
    Nov 2004
    Posts
    13
    Hi, thanks for your help so far. I generally understand what you're saying but I kind of need to be 'spoon fed' with these things (it took me many hours to just get the program how it is). Everything I'm trying is screwing up the code (namely with the dynamic arrays).
    Please give me more details/guidance for my particular problem.
    thanks,
    Sam
    Last edited by sammacs; 11-30-2004 at 05:29 PM.

  5. #5
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    >>Everything I'm trying is screwing up the code (namely with the dynamic arrays).
    >>Please give me more details
    Oh, the irony of it all.

    I suggest that you post some more details, i.e. what's screwing up, how do you know, what error messages are you getting, what behaviour are you seeing that is wrong? Stuff like that. More detail, like you said
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  6. #6
    Registered User
    Join Date
    Nov 2004
    Posts
    13
    Yes, quite.
    The reason I didn't post extra stuff is because I don't know what I'm doing. Sorry if it sounds like I'm scrounging for code but I've already posted my whole program (albeit not a very good one). I was hoping that manipulating it to contain a class would be easy for someone to do. I really don't know what I'm doing as all the examples I've found are not that similar to my program (no arrays for one)
    please help,
    Sam

  7. #7
    meow nbk's Avatar
    Join Date
    Jul 2004
    Posts
    45
    You really do need to post some details. What are you having problems with(give us the compiler message)?

    Also - if you don't know what you are doing, reread the material you are studying, or go back and read easier material.

    I say you need to be much more descriptive with the adjectives. It is hard to find the problem when the variable names are such: n, g, parray, narray, etc(most likely just me..)

  8. #8
    Carnivore ('-'v) Hunter2's Avatar
    Join Date
    May 2002
    Posts
    2,879
    Alright.. well, how much do you know about class'es and struct's? As far as I can see, it would be a fairly simple task to create a struct called Town that contains the population, name, etc.. Since in your program that you already have written, you have 3 arrays that are used "in parallel", i.e. narray[0] refers to the n of town 0, parray[0] refers to the p of town 0, etc. it should be easy to merge the three arrays (sort of) into a single array of Town structs.
    Code:
    struct Town
    {
       int area;
       int population;
       string name;
    };
    Then instead of creating a dynamic array of string, int, etc. for each property of the town, you can create a single dynamic array of Town's, and replace parray[x] with townArray[x].population, aarray[x] with townArray[x].area, etc.. Much prettier and easier to maintain too, I'll say.

    Hope this helps!

    P.S. Also, pay note to nbk's comment about descriptive variable names. 'parray' is less readable than 'populationArray' or even just 'population', since population[0] reads as "population zero" and populationArray[0] can be read as "populationArray at zero", but 'parray[0]' reads as "parray zero" or "pee-array zero"
    Last edited by Hunter2; 11-30-2004 at 07:05 PM.
    Just Google It. √

    (\ /)
    ( . .)
    c(")(") This is bunny. Copy and paste bunny into your signature to help him gain world domination.

  9. #9
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Guess my post was of no help since it didn't show you how to do what you want
    Woop?

  10. #10
    Registered User
    Join Date
    Nov 2004
    Posts
    13
    Thanks everyone for your contributions. bman - yours was the most helpful, or is that meant to be sarcasm. Regardless, I couldn't implement it (didn't know where my code fitted into your design (plus, what do all the std's mean - has your code been having lots of unprotected sex) and so I've consequently kind of given up. It was only a program for my own satisfaction (not for anyone or anything) so it doesn't matter all that much. If anyone would still do it for me it would be cool and appreciated but I think I need to go back to basics.
    Thanks again,
    Sam

  11. #11
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    Notice that using namespace std at the top of your program thats called a namespace. All of the standard functions, etc are in the std namespace. So instead of me putting a global namespace on my calls to the ones im using I just type it out.
    Woop?

  12. #12
    Registered User
    Join Date
    Nov 2004
    Posts
    13
    Yer, I just copy and paste the top couple of lines for every program without much thought for them as I'm told they're required for every program. Have you taken pity on my poor programming skills enough yet to enhance your earlier post.?
    cheers,
    Sam

  13. #13
    Toaster Zach L.'s Avatar
    Join Date
    Aug 2001
    Posts
    2,686
    Here is a link to this sites tutorial on structures. It might give you an idea of what to do.
    http://www.cprogramming.com/tutorial/lesson7.html

    plus, what do all the std's mean - has your code been having lots of unprotected sex
    Haha! Nice.
    The word rap as it applies to music is the result of a peculiar phonological rule which has stripped the word of its initial voiceless velar stop.

  14. #14
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Heres a skeletal version to see how it could look with a array of Towns declared dynamically.

    Code:
    struct Town
    {
      int population;
    };
     
    int main()
    {
      int ArraySize;
      cout << "enter number of towns to evaluate" << endl;
      cin >> ArraySize;
     
      Town * town = new Town[ArraySize];
      int i;
      for(i = 0; i < ArraySize; ++i)
      {
    	 cout << "enter name of town" << endl;
    	 cin >> town[i].population;
      }
     
      int largestTownIndex = 0;
      for(i = 1; i < ArraySize; ++i)
      { 
    	 if(town[i].population > town[largestTownIndex].population)
    		largestTownIndex = i;
      }
     
      cout << "the largest population is " << town[i].population;
     
      delete[]town
      return 0;
    }
    Edit, there, that's better.
    Last edited by elad; 12-01-2004 at 10:49 AM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ Classes: Use, Misuse...Confusion.
    By Snorpy_Py in forum C++ Programming
    Replies: 4
    Last Post: 10-23-2006, 01:46 AM
  2. Replies: 2
    Last Post: 07-28-2006, 02:59 PM
  3. Simple Question about Classes
    By Loctan in forum C++ Programming
    Replies: 5
    Last Post: 06-26-2006, 02:40 AM
  4. Fairly simple problem
    By fatdunky in forum C Programming
    Replies: 1
    Last Post: 11-14-2005, 11:34 PM
  5. Simple syntax question on classes
    By sean in forum C++ Programming
    Replies: 2
    Last Post: 07-07-2002, 08:30 PM