[try Beta version]
Not logged in

 
Facing Problem with getline()

Apr 29, 2013 at 9:16pm
Hi guys. I am trying to use getline function to take inputs but i can not understand how it is working.
1
2
3
4
5
6
7
8
9
10
11
  void Company :: getname()
{
	cout<<"Please enter number of companies you want to add: ";
	cin>>num;
	system("cls");
	for (int i=0; i<num; i++)
	{
		cout<<"Enter Company Name "<<i+1<<": ";
		getline(cin, name[i]);
	}
}

Its Output is:
Enter Company Name 1: Enter Company Name 2:

It is not taking any input for company name 1 but after that it is working.
Please help me with this. Thanks
Apr 29, 2013 at 9:21pm
closed account (Dy7SLyTq)
whats name? can you show its declaration please?
Apr 29, 2013 at 9:26pm
This is my code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <string>
#include <cstdlib>
#include <iomanip>
#include <conio.h>
#define MAX 500
using namespace std;
class Company
{	
	private:
		string name[MAX];
		int num;
	public:
		void getname();
		void showdata();
};
void Company :: getname()
{
	cout<<"Please enter number of companies you want to add: ";
	cin>>num;
	system("cls");
	for (int i=0; i<num; i++)
	{
		cout<<"Enter Company Name "<<i+1<<": ";
		getline(cin, name[i]);
	}
}
void Company :: showdata()
{
	system("cls");
	cout<<setw(20)<<"Name of Companies"<<endl;
	for(int j=0; j<num; j++)
	{
		cout<<j+1<<". "<<setw(10)<<name[j];
		cout<<endl;
	}
}
int main()
{
	Company Product;
	Product.getname();
	Product.showdata();
	getche();
	return 0;
}
Apr 29, 2013 at 9:28pm
You enter a number and press enter. cin>>num; reads the number but leaves the newline character in the stream. getline reads until it finds a new line character, so when getline is called next time it will find a newline character first thing making name[0] an empty string.

What you need to do is to get rid of the new line character from previous line before entering the loop that use getline. You can use the ignore function for this.
1
2
// Ignores one character.
cin.ignore();
1
2
// Ignores everything up to and including the next newline character.
cin.ignore(numeric_limits<streamsize>::max(), '\n');
Last edited on Apr 29, 2013 at 9:29pm
Apr 29, 2013 at 9:32pm
Thank you very much. It is working fine now.
Topic archived. No new replies allowed.