I have the following C++ function: void add\player(vector& players) { string…
- User
I have the following C++ function: void add_player(vector& players) { string player_name; string player_class; string dummy; PlayerClass pc; string player_sex; int player_gold;
cout << " Create a Mage, Warrior, Bowman, or Thief" << endl;
cout << "Name: "; getline(cin, player_name);
cout << "Class: "; getline(cin, player_class); pc = get_player_class_from_string(player_class); while (pc == PlayerClass::InvalidPlayerClass) { cout << " Invalid class, try again" << endl; cout << "Class: "; getline(cin, player_class); pc = get_player_class_from_string(player_class); }
cout << "Sex: "; getline(cin, player_sex);
cout << "Gold: "; cin >> player_gold; getline(cin, dummy); //consume newline
GamePlayer new_player; new_player.name = player_name; new_player.occupation = pc; new_player.gender = player_sex; new_player.gold = player_gold;
//add to vector players.push_back(new_player);
//add to file write_players_file(players); } Can you explain to me how the dummy variable is being used?
- Assistant
The
dummyvariable in the given C++ function is being used to consume the newline character left in the input stream after theplayer_goldinteger is read using thecinstatement.This is because when an integer is read using
cin, it only reads the integer value and leaves the newline character (\n) in the input stream. So when thegetlinefunction is called to read theplayer_sexstring, it immediately reads the newline character left in the input stream and stops reading, resulting in an empty string being stored in theplayer_sexvariable.To avoid this issue, the
getlinefunction is called again after reading the integer value, this time storing the input in thedummyvariable. Sincedummyis not used anywhere else in the function, it serves only to consume the leftover newline character and allow the nextgetlinecall to read the correct input.