cin.getline not working properly in a loop

I have written the code to get context and noun from the user. In every case there is one context and multiple nouns. I am able to get the context from the user but for the nouns the code runs the first loop with noun as an empty entity and then it works properly. I am not able to figure out why it is doing so.
Secondly i tried to declaring noun as a string the code works fine at that time but if the noun has spaces in between it just takes the first part of the noun.

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
1. 
 char context[20],n[50];

        cout << "enter the context:";
	cin.getline(context, sizeof(context));
	string context_1(context);

	
	
	if (datafile.is_open())
	{
		cout << "enter the number of nouns:";
		cin >> number; 	
		
		for (int i = 1; i <= number; i++)
		{
			
			
			cout << "enter the noun:";
			cin.getline(n,sizeof(n));
			string n_1(n);

2. 

char context[20];
string n;

        cout << "enter the context:";
	cin.getline(context, sizeof(context));
	string context_1(context);

	
	
	if (datafile.is_open())
	{
		cout << "enter the number of nouns:";
		cin >> number; 	
		
		for (int i = 1; i <= number; i++)
		{
			
			
			cout << "enter the noun:";
			cin >> n;
			
no it did not work. The code just got stuck.
closed account (48T7M4Gy)
When you go from cin to a line with getline precede the getline line with cin.clear(); followed by cin.ignore(1000, '\n');
kemort has the right idea. See also: http://www.LB-Stuff.com/user-input
Last edited on
closed account (48T7M4Gy)
See also: http://www.LB-Stuff.com/user-input
Tick :)
Thanks a lot it worked
Last edited on
Topic archived. No new replies allowed.