Doesn't read cin inside while loop

How can I make it so that the user enters the name for each sibling?
right now it just displays:
How many brothers and sisters do you have?4
A big family!
What's the name of your #1 sibling?
mark
What's the name of your #2 sibling?
What's the name of your #3 sibling?
What's the name of your #4 sibling?

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
 //Part 2 Coding
//Ronan Sullivan
#include <iostream>
#include <string>
using namespace std;
int main()
{
int siblings;
int name, x;
x = 1;

cout << "How many brothers and sisters do you have?";
cin >> siblings;
if (siblings < 0)
	{cout << "How could that be?\n";
	 cout << "Please enter a valid entry.\n";
	}
else if (siblings == 0)
	cout << "Oh, you were an only child.\n";
else if (siblings >=1 && siblings <= 3)
	cout << "Sounds like a nice size family.\n";
else if (siblings > 3)
	cout << "A big family!\n";
while (siblings >= 1)
	{
		cout << "What's the name of your #" << x++ << " sibling?\n";
		siblings--;
		cin >> name;
	}
return 0;
}
	
Last edited on
closed account (E0p9LyTq)
cin by itself is not the best for doing multiple inputs. Since there is an endline character already in the buffer after entering the first name each subsequent call to cin merely retrieves the endline.

You should use cin.get() instead of cin >>, and then "flush" cin's buffer by using cin.sync().

Rewritten code could be:

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
//Part 2 Coding
//Ronan Sullivan

#include <iostream>
#include <string>

using namespace std;

int main()
{
   int siblings;
   int name, x;
   x = 1;

   cout << "How many brothers and sisters do you have?";
   cin >> siblings;
   cin.sync();

   if (siblings < 0)
   {
      cout << "How could that be?\n";
      cout << "Please enter a valid entry.\n";
   }
   else if (siblings == 0)
   {
      cout << "Oh, you were an only child.\n";
   }
   else if (siblings >=1 && siblings <= 3)
   {
      cout << "Sounds like a nice size family.\n";
   }
   else if (siblings > 3)
   {
      cout << "A big family!\n";
   }

   while (siblings >= 1)
   {
      cout << "What's the name of your #" << x++ << " sibling?\n";
      siblings--;
      name = cin.get();
      cin.sync();
   }

   return 0;
}
Last edited on
"name" variable should be a string type
Changing it into a string worked, thanks!!!
Topic archived. No new replies allowed.