Hi,

Why the program skip 'read value' in second time? First time reading value is ok, but the problem will get after pressing 'Enter key' for the next time read.

//array of pointers to person objects

#include<iostream.h>

class Person
{
protected:
	char name[40];
  
public:
	void getname()
    {
		cout << "Enter name: ";
		cin.getline(name,40,'\n');
	}
 
    void putname()
    {
		cout << "\nName= "<< name;
    }
       
};

void main()
{
     Person *persptr[100];
     int n=0;
     char choice;
  
     do
	 {
		persptr[n] = new Person;
		persptr[n]->getname();
		
		n++;
 
		cout << "Enter another(y/n)? ";
		cin >> (choice,'\n');
		//cout << "\n";

      }while(choice=='y');
      
      for(int i=0;i<n;i++)
      {
		cout << "Person Number: " << i+1;
 
	    persptr[i]->putname();

		cout << "\n";
      }
  }

Could anyone please do check for me?

Regards,
zawpai

Recommended Answers

All 4 Replies

>>cin >> (choice,'\n');
What is that? All you need is cin >> choice; Since choice is a single character you might also have to flush the input buffer with all remaining characters so that the next cin will work correctly. See this thread that Narue wrote about how to do that.

Hi Ancient Dragon,

[TEX]>>cin >> (choice,'\n')[/TEX] is wrong because I am doing some testing. I think your way will be corrected. I need to flush the input buffer first before I read the next input. But, I am confusing and where should I put them in my sample code while i am reading Narue's code.

By the way, I will find out and read more from other.

Thanks,
zawpai.

you flush it right after cin

cin >> choice;
cin.ignore ( std::numeric_limits<std::streamsize>::max(), cin.widen ( '\n' ) );

Hi,

Thanks a lot. Now, I can do it well.

zawpai

Be a part of the DaniWeb community

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