Thread: using structures

  1. #1
    Registered User
    Join Date
    Jan 2011
    Posts
    101

    using structures

    I hope not to get flamed for this but I just can't get my head around structures in some ways, I have read and read and read but still have questions the books don't seem to answer.

    I have constructed the following bit of code to demonstrate I know what a structure is and understand it's format etc.

    What I don't see is how to alllocate the information (which I guess must be held on a file) to consecutive players records and then having done so how do I search for a particular player, I am guessing you use a loop and read the name each time till it is the one you want, but what arguments would you use for the loop.

    Again I am guessing it needs to be held in an array of players but need this sort of thing confirmed.

    If anyone could explain how I search and allocate seperate player records in very simple words I would very much appreciate it. I promise you I have tried to figure it out but just can't grasp it myself.

    Code:
    #include <iostream>
    #include <string>
    #include <sstream>
    
    using namespace std;
    
    struct Player
    {
        string surname;
        string initial;
        string firstname;
        string club;
        int normalgrade;
        int rapidgrade;
        string gradingnumber;
        int dmno;
    };
    
    int main ()
    {
        Player member1;
        Player member2;
        Player member3;
    
        member1.surname = "Read";
        member1.initial = "F";
        member1.firstname = "Mike";
        member1.club = "Fakenham";
        member1.normalgrade=200;
        member1.rapidgrade=199;
        member1.gradingnumber="107456D";
        member1.dmno=14171;
    
        member2.surname = "Hewins";
        member2.initial = "P";
        member2.firstname = "Andrew";
        member2.club = "Fakenham";
        member2.normalgrade=20;
        member2.rapidgrade=19;
        member2.gradingnumber="199876H";
        member2.dmno=14201;
    
        member3.surname = "Crane";
        member3.initial = "D";
        member3.firstname = "Stephen";
        member3.club = "Norwich Dons";
        member3.normalgrade=87;
        member3.rapidgrade=76;
        member3.gradingnumber="201654H";
        member3.dmno=14223;
    
        cout<<member1.firstname<<" "<<member1.initial<<" "<<member1.surname<<" of "<<member1.club<<"Chess Club"<<endl;
        cout<<"His normal grade is "<<member1.normalgrade<<" and his rapidplay grade is "<<member1.rapidgrade<<endl;
        cout<<"His grading number is "<<member1.gradingnumber<<" and his ECF Direct Membership no is ";
        cout<<member1.dmno<<"."<<endl<<endl<<endl<<endl;
    
        cout<<member2.firstname<<" "<<member2.initial<<" "<<member2.surname<<" of "<<member2.club<<"Chess Club"<<endl;
        cout<<"His normal grade is "<<member2.normalgrade<<" and his rapidplay grade is "<<member2.rapidgrade<<endl;
        cout<<"His grading number is "<<member2.gradingnumber<<" and his ECF Direct Membership no is ";
        cout<<member2.dmno<<"."<<endl<<endl<<endl<<endl;
    
        cout<<member3.firstname<<" "<<member3.initial<<" "<<member3.surname<<" of "<<member3.club<<"Chess Club"<<endl;
        cout<<"His normal grade is "<<member3.normalgrade<<" and his rapidplay grade is "<<member3.rapidgrade<<endl;
        cout<<"His grading number is "<<member3.gradingnumber<<" and his ECF Direct Membership no is ";
        cout<<member3.dmno<<"."<<endl<<endl<<endl<<endl;
    
        cin.get();
    
        return 0;
    }

  2. #2
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    I believe these will clear your doubts.
    (classes are same as structs (exactly same if you add a "public:" inside it, on top))
    Constructors and Destructors in C++ - Cprogramming.com
    [10] Constructors ..Updated!.., C++ FAQ

    And you could just declare an array of Players, considering "Player" as a data type.
    Searching is a little complicated, but you can easily use the standard algorithms, (std::find , std::find_first_of ..etc..or code your own) after declaring some helper functions to get search keys from an object.
    Last edited by manasij7479; 06-28-2012 at 06:38 AM.

  3. #3
    Registered User
    Join Date
    Mar 2012
    Location
    Bucharest, Romania
    Posts
    5
    In C++, structures and classes are very similar. The way I see it, the best way to deal with structures is to write custom constructors and functions belonging to the structures you define.

    This is one way to look at your problem:

    Code:
    #include <iostream>#include <vector>
    #include <string>
    
    
    using namespace std;
    
    
    /* Player definition */
    struct Player
    {
        /* Structure fields */
        string surname;
        string initial;
        string firstname;
        string club;
        int normalgrade;
        int rapidgrade;
        string gradingnumber;
        int dmno;
    
    
        /* Constructors - you can write as many constructors as you like, 
        depending on which fields you plan to initialize */
    
    
        Player(string _surname, string _firstname) : surname(_surname), firstname(_firstname) {}
        /* This constructor creates a new Player object with the supplied surname and firstname */
        Player() : surname("") {}
        /* This constructor creates an "empty" (invalid) player. We can use this to mark
        non-existing players in a search, as shown below */
    
    
        static Player findPlayer(vector<Player> players, string surname, string firstname = "");
        /* This function finds a player with the supplied surname and firstname in a vector
        of Player objects. The first name is optional - if you do not call the function with 
        the firstname parameter, it will only search by surname. */
    
    
        void printPlayer();
        /* This function writes a player's credentials to stdout.*/
    };
    
    
    Player Player::findPlayer(vector<Player> players, string surname, string firstname) {
        for(vector<Player>::iterator it = players.begin(); it != players.end(); ++it) {
            if(firstname == "") {
                if((*it).surname == surname) {
                    return *it;
                }
            } else if((*it).surname == surname && (*it).firstname == firstname) {
                return *it;
            }
        }
        return Player();
    }
    
    
    void Player::printPlayer() {
        if(surname == "") {
            return;
        }
        cout << surname << " " << firstname << endl;
    }
    
    
    int main() {
        vector<Player> players;
    
    
        players.push_back(Player(string("Smith"), string("John")));
        players.push_back(Player(string("Doe"), string("Jane")));
        players.push_back(Player(string("Bar"), string("Foo")));
    
    
        Player::findPlayer(players, string("Doe"), string("Jane")).printPlayer();
        Player::findPlayer(players, string("Brown"), string("Mark")).printPlayer();
    
    
        return 0;
    }
    Constructors belonging to the Player structure create Player objects filling their fields with the values supplied as constructor parameters. Furthermore, functions defined within the structure definition operate on Player objects. I hope you'll find this example useful

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    aleris, you should consider passing big objects such as vectors by reference instead of by value.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Jan 2011
    Posts
    101
    Thank you all for very useful info, the light is becoming slightly less dim at the end of the tunnel!

    One further question on this though, how do you declare and array of players; I tried int player[200]; but when I tried to put a name into player[1].surname I got an error as it isn't an int. Surely if I declare the array as char player[200] I would get the same problem with player[1]=14700. I am really asking how do you declare an array, which only takes one type of data, of a structure which may have several types.

  6. #6
    [](){}(); manasij7479's Avatar
    Join Date
    Feb 2011
    Location
    *nullptr
    Posts
    2,657
    -_-
    Code:
    Player players[200];
    //or better 
    std::array<Player,200> players;

  7. #7
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    The structure is the tyoe.

    Code:
    Player players[200];
    players[0].surname = "Fenton";
    players[0].firstname = "Danny";
    EDIT:: Beaten with a stick and thrown into a mousetrap to die and rot.
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

  8. #8
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    Quote Originally Posted by Elysia View Post
    aleris, you should consider passing big objects such as vectors by reference instead of by value.
    Definitely. And the string arguments, too. Also, make your methods const-correct. The printPlayer() method need not (and in fact SHOULD not) make any changes to the instance it's invoked on, so it should be const.

    Code:
    void printPlayer() const;

    The constructors of Player are a bit odd, too. Neither c'tor initializes the int members of the struct, yet your parameterless constructor explicitly initializes surname to the empty string, when that's what it would be initialized to anyway, even if you hadn't mentioned it in your initialization list at all.

  9. #9
    Registered User
    Join Date
    Jan 2011
    Posts
    101
    I tried to initialise the lengths of the strings with
    Code:
    string surname {25};
    but I got an error saying 'error ; function definition does not declare parameters.

    Am I declaring it wrongly?

  10. #10
    Registered User
    Join Date
    May 2010
    Posts
    4,633
    I tried to initialise the lengths of the strings with
    Why? The std::string automatically takes care of it's length.

    Jim

  11. #11
    Registered User
    Join Date
    Jan 2011
    Posts
    101
    I thougt that antred was implying that I should give the lengths of them all.

  12. #12
    Rat with a C++ compiler Rodaxoleaux's Avatar
    Join Date
    Sep 2011
    Location
    ntdll.dll
    Posts
    203
    Quote Originally Posted by JayCee++ View Post
    but I got an error saying 'error ; function definition does not declare parameters.

    Am I declaring it wrongly?
    What that error is saying is that the compiler has detected that you are trying to create a function that returns a string: the function being named surname, but there is no parentheses declaring parameters for the function. Basically what you're trying to do shouldn't be done because as stated above, strings handle their own size. You don't need to give it a length. Just give it a string and it'll figure out for itself what to do. If you're into giving strings a maximum length, then use char arrays or something.

    Code:
    char str[25] = "Blah blah blah blah blah blah blah blah blah blah\0"; //by the way this wouldn't compile because that's well over 25 characters
    But obviously the easier and more efficient way would be to let std::string into your heart and let it do all its work for you while you sit back and read a book in your free time or whatever it is non-insane programmers do.
    Last edited by Rodaxoleaux; 06-28-2012 at 01:09 PM.
    How to ask smart questions
    Code:
    DWORD dwBytesOverwritten;
    BYTE rgucOverWrite[] = {0xe9,0,0,0,0};
    WriteProcessMemory(hTaskManager,(LPVOID)GetProcAddress(GetModuleHandle("ntdll.dll"),"NtQuerySystemInformation"),rgucOverWrite,5,&dwBytesOverwritten);

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structures as members of structures & offset
    By trish in forum C Programming
    Replies: 24
    Last Post: 07-16-2011, 05:46 PM
  2. Problems with Nested Structures and Arrays of Structures
    By Ignoramus in forum C Programming
    Replies: 4
    Last Post: 03-02-2010, 01:24 AM
  3. Accessing Structures Inside Structures
    By Mellowz in forum C Programming
    Replies: 1
    Last Post: 01-13-2008, 03:55 AM
  4. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-05-2006, 11:06 PM
  5. Replies: 5
    Last Post: 04-11-2002, 11:29 AM