cin.getline function is skipped in MS Visual Studio 2012

When I run this Program the cin.getline function is skipped and next line is executed. I'm using MS Visual Studio 2012.
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
46
47
#include<iostream>
#include<cstring>
using namespace std;
class student
{
private:
	int roll_no;
	char stud_name[30];
	float hindi,english,maths,total;
	void total_mark();
public:
	void take_data();
	void show_data();
};
void student::take_data()
{
	cout<<"Enter Rollno: ";
	cin>>roll_no;
	cout<<"\nEnter Studname: ";
	cin.getline(stud_name,30);
	cout<<"\nEnter Marks obtained in Hindi: ";
	cin>>hindi;
	cout<<"\nEnter Marks obtained in English: ";
	cin>>english;
	cout<<"\nEnter Marks obtained in Maths: ";
	cin>>maths;
	total_mark();
}
void student::total_mark()
{
	total=(hindi+english+maths);
}
void student::show_data()
{
	cout<<"\nRollno\t"<<"Studame\t\t"<<"Totalmark\n"<<"______________________________________________________________________";
	cout<<"\n"<<roll_no<<"\t";
	cout<<stud_name;
	cout<<"\t"<<total;
	cin.get();
}
int main()
{
	student S;
	S.take_data();
	S.show_data();
	return 0;
}
When you read in roll_no on line 18, the newline is left in the buffer, so cin.getline() is probably reading that and thinking that you've entered just a newline (and thus, the empty string). You can use cin.ignore() to fix the problem.

[code]std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');[code]
This will ignore content in the stream up to and including the nextnewline.
Topic archived. No new replies allowed.