I have this problem. This program runs well except that it skip the value of the first item in list. I think it is because of the cin.ignore(). But if I don't use the cin.ignore(). The cin will only read the first input and none after that. Help?

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

class list				//  list class
{
	private:
		string *Data;
		int size;
		int num;

	public:
		list()			// constructor
		{
			size =  1;
			num = 0;
		}             
             
		void add();		// member function
		void display();
};



void list :: add()
{
	const int SIZE_INPUT = 50;
	char choice;
	char temp_input[SIZE_INPUT] = "";

	do
	{
		Data = new string[size];
		cout << "\n Enter item\t: ";
			
		if(num>0)
		{
			cin.ignore(INT_MAX, '\n' ); 
		}
			
		cin.getline(temp_input, sizeof(temp_input));
			
		Data[num] = temp_input;
			
		num++;
		size++;
		
		cout<<"Continue to Enter Item (Y=Yes/N=No)\t:\t";
		cin >> choice;

	} while(tolower(choice) != 'n');
}

//This function only display the last item. But if I try to display item one by one, no problem except that I cant display the first item (because of the cin.ignore?).
void list :: display()
{
	int i;

	cout << num << endl;

	for (i=0; i<num; i++)
	{
		cout << Data[i] << endl;
	}
}

int main()
{
	list testing;

	testing.add();
	testing.display();

	system("PAUSE");
}

> Data = new string;
Not only does this leak memory, it also loses all your previous input.
You need a way of expanding your array of lines.
Have you considered that std::vector would be ideal for this.

Put the cin.ignore directly after any I/O functions which leave newlines behind.

Replace your line 9 with "string Data[20];"
also don't forget to comment line 34.

RenjitVR, if I do that, means I can only input maximum 20 string item right? What I'm trying to get is unlimited input. Something like a simple dynamic array.

** Thanks Jencas and Salem for your reply :)

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.