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
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');