void insert()
{	
  	counter++;
        char id [12];
	string title;
	string author;
	int year;
	char num_id[12];
   	
	borrow *newptr,*p,*q;//declare
	p = head;
	q = NULL;
	 //counter++; 
	newptr = new borrow;//declare
			
	cout<<"\nEnter your ID: ";
	cin>>newptr->id;
	cout<<"\nTitle of the book: ";
	cin>>newptr->title;
    getline (cin, newptr->title);
	cout<<"\nAuthor: ";
	cin>>newptr->author;
	getline (cin, newptr->author);
	cout<<"\nYear: ";
	cin>>newptr->year;
	newptr->next=NULL;
	 if(head==NULL)
    {
 	 head=newptr;
 	}
  else
  {
	while(p!= NULL && strcmp(newptr->id,p->id)>0)
	//while(p!= NULL && (newptr->id > p->id && newptr->id > p->id))
	{
		q=p;
		p=p->next;
	}
	if (q==NULL)
	{
		newptr->next=head;
		head=newptr;
	}
	else
	{
		newptr->next=p;
		q->next=newptr;
	}
  }

}
		
void display()
{	int n=0,newptr;
	pinjambuku *cur;
	cur = head;

	while (cur != NULL)
	{ 
	cout <<cur->id<<endl;
	cout <<cur->title<<endl;
	cout <<cur->author<<endl;	
	cout <<cur->year<<endl;
	cur=cur->next;
	n++;
	}
	cout<<" Total of ID  :"<<n<<endl;
}

*** when i entered harry potter in the title, it appear potter and the same goes to the author which when i entered jack sparrow, it will print sparrow, anyone can help me?

Recommended Answers

All 2 Replies

Just use getline() when you read strings from the user. Remove cin>>newptr->title and cin>>newptr->author from your code.

Beware of mixing calls to >> and getline() in the same program. The default termination character for getline() is the newline char. getline() will stop putting additional information into the target string whenever if finds the terminating char. getline() will remove the terminating char from the input stream. White space characters (newline, tab, etc) are the terminating characters for >>. >> does not remove the terminating char from input stream. >> and getline() fequently use the same input stream, for example, both use cin in your program.

In your program >> is called before getline() is called and is terminated by newline. getline() is using the default newline char as the terminating char. Therefore, the first thing getline sees is the newline char left in the input stream by the preceding call to >> and it doesn't put the expected information into the expected variarble. It doesn't matter whether >> is called immediately before getline() or not in the programming code.

Options to deal with this are:
1) Don't mix >> and getline() in the same program.
2) Attempt to clear the input stream before every call to getline() if you do mix >> and getline().

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.