while loop and string limit question

Hey guys i need some help here. I'm supposed to write a program that asks for a users id into a string. the string can only be 4 digits. Any idea how i can limit the string to only 4 characters?

And i also have to make a certain while loop but im getting some problems with it.

1
2
3
4
5
6
7
8
9
10
11
12
13
char gender;
	string x;
	cout << "What is your gender?" << endl;
	cin >> gender;
	
	while (( gender != 'M') && (gender != 'm') && (gender != 'f') && (gender != 'F'));
	{ 
		cout << "Please enter F or M." << endl;
		cin >> gender;
	}
	cout << gender;
	x = gender;
	return x;
Try this ...

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>
#include <string>

using namespace std;

int main ()
{
   string id = " ";
   char gender = ' ';

   cout << "Enter your ID. ID must be of 4 characters long: ";
   getline (cin, id);
   
   while ( id.size() != 4 )
   {
      cout << "Your ID must be 4 characters long. Enter ID again: ";
      getline (cin, id);
   }

   cout << "\nEnter your gender: ";
   cin >> gender;

   while ( !(gender == 'm' || gender == 'M' || gender == 'f' || gender == 'F') )
   {
      cout << "Please, enter F or M: ";
      
      cin.clear();
      cin.ignore (1000, '\n');

      cin >> gender;
   }

   cout << endl << id << ' ' << gender << endl;
     
   return 0;
}


Happy coding...
Last edited on
thanks, worked like a charm. I figured out the ID part shortly before checking up on here. But it solved my gender issues. Thanks
Topic archived. No new replies allowed.