Skip to content

Commit e150a0e

Browse files
committed
Adding input validation
1 parent 6e5d003 commit e150a0e

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

shm/Game.cpp

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#include "Game.hpp"
2-
2+
#include <limits>
33
class Map;
44

55
Game::Game(size_t money, size_t gameDays, size_t finalGoal)
@@ -125,12 +125,15 @@ void Game::printStoreCargo()
125125
currentStore_->printStoreCargo();
126126
}
127127

128+
129+
128130
void Game::buyCargo()
129131
{
130132
int cargoElement = 0;
131133
size_t amount = 0;
132134
std::cout << "Choose cargo: ";
133135
std::cin >> cargoElement;
136+
134137
if (cargoElement >=0 && cargoElement < currentStore_->storeCargo.size())
135138
{
136139
std::cout << "Choose amount: ";
@@ -139,7 +142,9 @@ void Game::buyCargo()
139142
}
140143
else
141144
{
142-
std::cout << "There is no such cargo in this store." << '\n';
145+
std::cout << "There is no such cargo in this store." << '\n';
146+
std::cin.clear();
147+
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
143148
buyCargo();
144149
}
145150

@@ -159,7 +164,9 @@ void Game::sellCargo()
159164
}
160165
else
161166
{
162-
std::cout << "There is no such cargo in this ship." << '\n';
167+
std::cout << "There is no such cargo in this ship." << '\n';
168+
std::cin.clear();
169+
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
163170
sellCargo();
164171
}
165172
}

0 commit comments

Comments
 (0)