Thread: Need help with structures

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    6

    Need help with structures

    Code:
    //This code is supposed to ask the user to enter 5 players, name
    //number and points scored.  It then calculates the total score of
    // all players, added together.  It shows each individuals name, #
    //and score.  Then it displays the players scores added together.
    //Could someone please try the code and see if you can see why
    //my program doesn't iterate through the code in the proper way?
    
    
    #include <iostream>
    #include <iomanip>
    
    using namespace std;
    
    struct PlayerInfo
    {
    	char name[30];
    	int playernumber;
    	int points;
    };
    
    
    int main()
    
    {
    	int allplayerstotals;
    	PlayerInfo players[5];
    	int index;
    
    	//Get player information.
    	cout<<"Enter 5 players names, numbers and points scored.\n";
    	for (index = 0; index < 5; index++)
    	{
    		cout<<"Player # "<<(index + 1)<<"'s name? : ";
    		cin.getline(players[index].name, 30);
    		cout<<"Player's number? : ";
    		cin>>players[index].playernumber;
    		cout<<"Player's points? : ";
    		cin>>players[index].points;
    		
    	
    	}
    	//Display player stats.
    	for (index = 0; index < 5; index++)
    	{
    		
    		allplayerstotals += players[index].points;
    		cout<<"Player # "<<(index + 1)<<"stats :\n";
    		cout<<"Name :"<<players[index].name<<endl;
    		cout<<"No.# :"<<players[index].playernumber<<endl;
    		cout<<"Points:"<<players[index].points<<endl;
            allplayerstotals += players[index].points;
    	}
    		cout<<"All players' totals together are :"<<allplayerstotals;
    	return 0;
    }

  2. #2
    Registered User
    Join Date
    Mar 2004
    Posts
    220
    I'm not sure what's happening to answer your original question about the incorrect looping just yet, I'll get back to you on that when I find a solution.

    To fix some other issues.
    Code:
    std::cout << std::endl;
    is nice, or the equivalent
    Code:
    std::cout << "\n";
    I would also suggest using unsigned integers instead of signed integers in the places that you do use them. As well as defaulting your values before you use them, example:
    Code:
    unsigned int allplayerstotals = 0;
    unsigned int index = 0;
    OS: Windows XP Pro CE
    IDE: VS .NET 2002
    Preferred Language: C++.

  3. #3
    Registered User
    Join Date
    Apr 2005
    Posts
    6
    I really need help with this. This seems to be getting into another discussion.

  4. #4
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    Ok, I'll delete my post. Good luck with your program.
    Last edited by 7stud; 04-19-2005 at 11:51 PM.

  5. #5
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,820
    1. Please don't add !!!!!!!!!!!!!!!!!!!!!!!! to your thread title it is quite annoying.

    2. Tell us what your problem is so we can help with it. Post errors and things that you program is doing when it is not supposed to be doing them.

    3. Mixing getline and cin>> are a bad idea unless you clean up after cin>>. cin>> ignore's things such as a newline charcter getline does not. So after you hit enter in your cin>> it leaves a '\n' which your getline picks up on.

    4. Don't be rude to people who are trying to help you.
    Woop?

  6. #6
    Registered User
    Join Date
    Apr 2005
    Posts
    6
    I'm not trying to be rude but the most anoying thing on all forums are the sidebars. You post a forum and someone else gets a discussion going on the side. I used to edit for dmoz and this used to aggravate the editors most of all.

  7. #7
    Registered User
    Join Date
    Apr 2003
    Posts
    2,663
    I posted a long detailed explanation of your problem, and you rejected it. I also posted a short note that pointed out that the other response was mistaken in saying your omission of std:: was the problem. You were free to read them both, read one or the other, or skip both. I didn't think you were being rude, and I realize some people can explain things better than others, and since you didn't find my post helpful, I deleted it--mostly out of frustration. Again, I did not feel insulted, and I realize that you didn't understand what I was talking about.

    However, this is a discussion forum, and if you don't want your code discussed, then I suggest you get help from a teacher or somewhere else. That may be blunt, but it is not intended to be rude, so I hope you don't take it that way. In discussions on forums, lots of times the people discussing a post may learn as much about some side issue as the original poster learned about their code. That's the way it works, and most of us are here trying to learn stuff, so usually it works out for everyone. Good luck.
    Last edited by 7stud; 04-20-2005 at 02:12 AM.

  8. #8
    Registered User
    Join Date
    Apr 2005
    Posts
    5

    Lightbulb Try this

    Quote Originally Posted by prog-bman
    3. Mixing getline and cin>> are a bad idea unless you clean up after cin>>. cin>> ignore's things such as a newline charcter getline does not. So after you hit enter in your cin>> it leaves a '\n' which your getline picks up on.
    prog-bman has a point here. When you use strings, or character arrays, it is usually good to put a cin.ignore(); after the input statement. This helps "clean up" because your program will still be looking for the rest of those characters. This command tells the computer to ignore the rest of the line.

    Code:
    for (index = 0; index < 5; index++)
    	{
    		cout<<"Player # "<<(index + 1)<<"'s name? : ";
                                    cin.ignore();
    		cin.getline(players[index].name, 30);
    		cout<<"Player's number? : ";
    		cin>>players[index].playernumber;
    		cout<<"Player's points? : ";
    		cin>>players[index].points;
    	}
    I added the cin.ignore(); statement just before the cin statement for the name. I ran it in my compiler and it worked just fine.

  9. #9
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    Problem 1)

    int allplayerstotals;

    Until you assign a value to allplayerstotals it has a useless/garbage value in it. When you try to add a meaningful value to the useless value in the following line:

    allplayerstotals += players[index].points;

    the value is still useless. Therefore, assign a meaningful value to allplayerstotals or initialize it to a meaningful value before you try to use it, as was suggested earlier.

    Problem 2)

    I see no reason to have the above line twice in the same loop. I'd suggest you delete one of the lines.

    Problem 3)
    Short answer to "iteration" problem: try adding a line like:

    cin.ignore();

    between these two lines:

    cout<<"Player # "<<(index + 1)<<"'s name? : ";
    cin.getline(players[index].name, 30);

    See replies from progman and jamesmac14.


    Long winded, educational type answer to "iteration" problem (prbably similar to 7studs, but maybe less technical):

    Start with how cin works with the >> operator and the getline() method.

    First, user input is (usually) buffered. That means that the keystrokes are stored in an internal buffer where cin retrieves the keyed in input using the >> operator or the getline() method or whatever, and processes the information entered by the keystrokes in the input buffer into a variable designated by >> or getline(). Pushing the enter key, causing a newline char to be entered into the input buffer behind the other keystrokes, (generally) signals the program to call cin to come retrieve the information.

    The >> operator ignores leading whitespace and stops input at the first whitespace after a nonwhitespace char has been found. The terminating whitespace is not removed from the input buffer by >>. This can be a very convenient behaviour, but under certain circumstances it can also lead to problems, see below.

    The getline() method doesn't ignore whitespace chars. This can be a very useful feature, too. For example, you can input the first name and last name of a given person in the same string, even if the two names are separated by a space using getline(), but you can't with >>. This can also be a problem, though. For example, how does getline() know when to stop input if it doesn't stop input at the first whitespace char like >> does? The answer is getline() uses two additional parameters (that aren't necessary with >>) to determine when to stop input. The second parameter of getline() indicates a maximum total number of char that getline() should read into the variable IF the termination char passed as the third parameter isn't found before then. The third parameter has a default value of newline char, which is a whitespace char. The terminating char is removed from the input buffer, if it is what caused termination of input.

    Fine and dandy you say, but how does this impact my code? Well, when you combine getline() and >> in the same code you can trip yourself up. Here's how, using your example.

    Code:
    for (index = 0; index < 5; index++)
    {
      cout<<"Player # "<<(index + 1)<<"'s name? : ";
      cin.getline(players[index].name, 30);
    this should go fine, without a hitch, when index = 0. The first 30 char, whitespace or not, will be put into players[index].name, unless the newline char is encountered first. If the newline char is encountered before 30 char have been read, then input will be stopped and the newline char removed from the buffer. Assuming less than 30 char were input by the user for the players name, the input buffer is now empty. Alls fine. Then the following lines are encountered:

    cout<<"Player's number? : ";
    cin>>players[index].playernumber;
    cout<<"Player's points? : ";
    cin>>players[index].points;

    There is no leading whitespace for the first >> to ignore, but the first >> will leave the terminating newline char in the input buffer which will be ignored by the second >> which will again leave the terminating newline char in the input buffer. So far so good. The first players information is probably entered fine. But, let's see what happens when index is 1. The call to getline will fails to put anything into player[1].name. It skips right over the line without doing anything (anything visible that is). Why? Because the first char in the input buffer is the newline char left over from the second call to >> when index was zero. When getline() finds the first char to be newline it stops input into players[1].name without putting anything in it, and removes that initial newline char from the input buffer. That means that players[1].name is still garbage since nothing meaningful has be assigned or intialized to that space in memory (see problem # 1 above). On top of that, whatever alphabetical chars the user entered for the players name are still in the input buffer and when >> trys to put a char in an int, it may well go into an infinite loop/hang/crash your program, or worse, provide illogical data in the various struct fields without "notifying" you of the problem in the first place.

    What to do? Options include: Learn how >> and getline() work. Learn how to use the ignore() method if you are going to mix >> and getline() in the same program. Obtain user's name by two calls to >> and concatenate the two strings into one if you want rather than making one call to getline() because it allows you to use whitespace in strings. Etc. Bottom line, there are a variety of fixes you can use to deal with the problem, once you know it exists. You will become aware of the problem by experience or through somebody else (like the others who have posted) providing you the pertinent information.
    You're only born perfect.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 07-11-2008, 07:39 AM
  2. Structures, passing array of structures to function
    By saahmed in forum C Programming
    Replies: 10
    Last Post: 04-05-2006, 11:06 PM
  3. Input output with structures
    By barim in forum C Programming
    Replies: 10
    Last Post: 04-27-2004, 08:00 PM
  4. pointers to arrays of structures
    By terryrmcgowan in forum C Programming
    Replies: 1
    Last Post: 06-25-2003, 09:04 AM
  5. Methods for Sorting Structures by Element...
    By Sebastiani in forum C Programming
    Replies: 9
    Last Post: 09-14-2001, 12:59 PM