Reputation: 55
When i input the Id , Name And Add . Id And Name are input successfully but,not Name.
The Output shows Only Id And Name but, Name shows In Add Place.
Can anyone tell me getline() Function Of initialization Is Correct Or Not ?
#include<iostream>
using namespace std;
class Stu_Record
{
private:
int Id;
char Name[20];
char Add[20];
public:
void Input_Data();
void Display_Data();
};
void Stu_Record::Input_Data()
{
cout<<endl<<"Enter Id,Name And Address:";
cin>>Id;
cin.getline(Name,20);
cin.getline(Add,20);
}
void Stu_Record::Display_Data()
{
cout<<endl<<"Id Is :"<<ends<<Id;
cout<<endl<<"Name Is :"<<ends<<Name;
cout<<endl<<"Address Is :"<<ends<<Add;
}
int main()
{
Stu_Record S;
S.Input_Data();
S.Display_Data();
return(0);
}
Upvotes: 0
Views: 73
Reputation: 155403
cin>>Id;
reads the Id
in, but doesn't strip the newline that the user would have entered after it. The next call to getline
sees that the next character is a newline, consumes it, and happily fills in Name
as an empty string. The final getline
then fills in what you expected to go to Name
as the value of Add
(and the value intended for Add
is never read at all).
A simple fix would be to discard the rest of the line after reading in Id
, so you don't have the garbage lying around when you try to read in Name
. One way of doing that is the ignore
method on input streams:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
which will throw away everything following the data read to populate Id
through to the next newline character, so if the user enters:
1 why did I type this garbage, oh the humanity
Fred
Where am I?
you'll get an Id
of 1
, ignore the rest of the line, a Name
of "Fred"
, and an Add
of "Where am I?"
.
Upvotes: 3