I am having trouble with a program that I have written in C++. My problem is that I can't put the name information into my structure. I am able to add in the "name" the first time around, however, on the second loop it simply skips it and goes on to the "HC" input. Here is my code, can anyone tell me why it won't allow me to input a name on loop #2?

Thanks for your help!

#include <iostream>

const int Arsize = 3;

struct handicap
	char name[20];
	int hc;
}people [Arsize];
void display (handicap score);

using namespace std;
int main()
	int i;
	cout<<"Please input name and hc."<<endl;
	for (i=0;i<3;i++)
		cin.getline(people[i].name, 20);//<--my problem exists here on loop #2
	cout<<"You have entered the following info:"<<endl;
for (i=0;i<3; i++)
return 0;
void display (handicap score)

Recommended Answers

All 5 Replies

How many times during registration were you pointed to The Rules? Why would you ignore them?

When reading an integer, cin leaves the \n in the buffer. The next cin sees that and continues on thinking it was his. You have to clear the input stream before reading strings if they are followed by reading numbers.

Thanks for the feedback, however, me being brand new at this is causing me some difficulty. I am not having an issue with the cin integer input. The loop is allowing me to loop back up, however, it doesn't allow me to input text and only numbers during the 2nd and 3rd loops. Without being completely obvious(I really do want to figure this out on my own), would you go more indepth on your feedback. For example, I have tried using cin.get, but should I use clear?

Member Avatar

Clearing the streams can get tricky.

A very simple solution would be to read everything as strings using cin.getline or getline and them convert to integers where necessary.

It also looks like you haven't declared your struct anywhere in main().

// ...
  for (i=0;i<3;i++)
    cin >> ws ; // eat up whitespaces that may be left in the buffer
    // or cin.ignore
    cin.getline(people[i].name, 20);//<--should be ok now
    cin>>people[i].hc; // you will still have problems if the user
                   // enters non integer values here. or if the user 
                   // entered more than 19 characters for the name. to fix it
                   // see the first solution given in
                   // http://www.daniweb.com/forums/thread90228.html
  // ...

Hey thanks. We definitely haven't touched the "cin>>ws;" in class yet. It makes sense now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.