'Getline & cin.ignore in c++
I know there are similar questions to mine, but I checked alot of them and didn't find the answer so I hope someone can help me.
So what I am trying to do is store some strings into arrays, but some of these strings could consist of more than one word, so I searched the internet and found out I have to use cin.ignore()
and getline
. I used them, as seen in my code below, but the error happens in the second and third string where the first letter of surname[0]
and address[0]
is removed. So why is that?
Here is my code:
int size;
cout<<"Please enter the number of entries"<<endl;
cin>>size;
cin.ignore();
string* firstname=new string[size];
string* surname=new string[size];
string* address=new string[size];
cout<<"First Name"<<endl;
for (int i=0;i<size;i++)
getline (cin, firstname[i]);
cout<<"Surname"<<endl;
cin.ignore();
for (int i=0;i<size;i++)
getline (cin, surname[i]);
cout<<"Address"<<endl;
cin.ignore();
for (int i=0;i<size;i++)
getline (cin, address[i]);
for (int i=0;i<size;i++)
{
cout<<"First Name "<<firstname[i]<<endl;
cout<<"Surname "<<surname[i]<<endl;
cout<<"Age "<<address[i]<<endl;
}
EDIT: Sample Input/Output
Please enter the number of entries
4
First Name
John
Michael
Daniel
Radu
Surname
Laaksonen
Taro
Albot
Smith
Address
123 Larkin Street
900 Larkin Street
823 Larkin Street
283 Larkin Street
**First Name John
Surname aaksonen
Address 23 Larkin Street
First Name Michael
Surname Taro
Address 900 Larkin Street
First Name Daniel
Surname Albot
Address 823 Larkin Street
First Name Radu
Surname Smith
Address 283 Larkin Street**
Bold is the program's output. See how the L in Laaksonen is missing and the 1 in 123 is missing.
Solution 1:[1]
getline()
reads and discard delimiter (reference), you have to use cin.ignore()
only when you read your first integer:
cout<<"First Name"<<endl;
for (int i=0;i<size;i++)
getline (cin, firstname[i]);
cout<<"Surname"<<endl;
// Remove this: cin.ignore();
for (int i=0;i<size;i++)
getline (cin, surname[i]);
cout<<"Address"<<endl;
// Remove this: cin.ignore();
for (int i=0;i<size;i++)
getline (cin, address[i]);
That said you may avoid standard arrays, a std::vector<std::string>> firstNames
would be more appropriate.
Solution 2:[2]
An alternative would be to read all using getline(), and parse the integer (using atoi or some such) yourself, avoiding the need for ignore entirely.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Adriano Repetti |
Solution 2 | Scott Hunter |