While loop executing when it's not meant to

Okay so the following code works as expected EXCEPT for some reason if I put a space when inputting the name e.g. (Mitchell Maygs) the while loop will continuously execute and I don't mean once I mean it will repeatedly output the line

cout << "Invalid type. Please enter either p (permanent) or c (casual)" << endl;

until it crashes. Why does the use of the spacebar cause this and how do I fix it?

Here's the code

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
void add()
{
	string type;
	cout << "Permanent or Casual? (p/c)" << endl;
	cin >> type;
	while (!(type == "p" || type == "c")){
		cout << "Invalid type. Please enter either p (permanent) or c (casual)" << endl;
		cin >> type;
	}
	cout << "Enter ID number: ";
	string IDno;
	cin >> IDno;

	find(IDno);
	if(currentEmployee != NULL){
		cout << "ID number already exists" << endl;
		currentEmployee = NULL;
		return;
	}

	cout << "Enter Employee name: ";
	string name;
	cin >> name;

	cout << "Enter Employee pay rate: ";
	double payRate;
	cin >> payRate;

	if(type == "p"){
		Permanent *p = new Permanent(IDno, name, payRate); 
		data[empCount] = p;
		empCount++;
		cout << "New permanent employee created" << endl;
		currentEmployee = NULL;
	}
	else if(type == "c"){
		Casual *c = new Casual(IDno, name, payRate);
		data[empCount] = c;
		empCount++;
		cout << "New casual employee created" << endl;
		currentEmployee = NULL;
	}
}



Cheers.

Edit: Well I changed the code so the space doesn't need to be entered in the program like so;

1
2
3
4
5
6
7
	cout << "Enter Employee's first name: ";
	string fname;
	string lname;
	cin >> fname;
	cout << "Enter Employee's last name: ";
	cin >> lname;
	string name = fname + " " + lname;


Seemingly this works. I'd still love for someone to explain to me why the spacebar character messes up the function though. Thanks.
Last edited on
Try this:
1
2
cin >> type;
cin.sync();

When a user types something and then hits enter, cin only reads until the first white space/newline (by default). Therefore, there are extra characters that'll remain in the stream which causes cin to have a bad state. As is the case of your example, that loop continues indefinitely since the stream is never put into a good state again.
Last edited on
Topic archived. No new replies allowed.