Read a quantity someone typed
A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.
- Whitespace around the number is fine and is ignored.
- Only digits are allowed — no sign, no decimal point, no spaces inside.
- The value must be between 1 and 999.
- Anything else gives -1.
validQuantity(text: string) → int
C++ needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
int validQuantity(std::string text) {
}
Worked examples
| Call | Result |
|---|---|
validQuantity(std::string("5")) | 5 |
validQuantity(std::string(" 12 ")) | 12 |
validQuantity(std::string("999")) | 999 |
validQuantity(std::string("0")) | -1 |
Hint
Trim, reject an empty result, then check every remaining character before you convert.
Reference solution in C++
int validQuantity(std::string text) {
size_t a = text.find_first_not_of(" \t\n\r");
if (a == string::npos) return -1;
size_t b = text.find_last_not_of(" \t\n\r");
string t = text.substr(a, b - a + 1);
for (char c : t) if (c < '0' || c > '9') return -1;
if (t.size() > 4) return -1;
int n = std::stoi(t);
return (n >= 1 && n <= 999) ? n : -1;
}