how to input in cin.getline() using function

the problem is when it goto first name input it takes but next time its ignore it how to fix this
its not finished but its making problem in taking name with space
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
#include <iostream.h>
#include <stdlib.h>
using namespace std;
struct student
{
	char name[50];
	int id;
};
student input()
{
	 student s;
         cout << "enter name :";
	 cin.getline(s.name,50);	
         cout << "enter id :";
	 cin >> s.id;
	 return s;
}
void main()
{
	student s[5];
	//student *p;
	int i;
	//p = s;
	for ( i = 1; i < 5; i++ )
	{
		
		s[i] = input();
	}
	for ( i = 0; i < 5; i++ )
	{
		cout << "student " << s[i].id << endl;
		cout << "student " << s[i].name << endl;
	}
	system( "pause" );
}
There are two things
first you are returning a local variable. The memory of that variable will be released after the function returns
1
2
3
4
5
6
7
8
9
student input()
{
	 student s;
         cout << "enter name :";
	 cin.getline(s.name,50);	
         cout << "enter id :";
	 cin >> s.id;
	 return s;
}


should be
1
2
3
4
5
6
7
void input(student &s)
{
         cout << "enter name :";
	 cin.getline(s.name,50);	
         cout << "enter id :";
	 cin >> s.id;
}


second your array is of 5 students and you are taking in only 4 (the for look will go from 1-4)
Last edited on
Topic archived. No new replies allowed.