Drill

ProblemsC++ › validation

Read a quantity someone typed

easyvalidationParsingStringsC++

A stock adjustment screen takes a quantity as free text, and the parser refuses anything it cannot trust.

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.

Solve it in Python →

Where you start

int validQuantity(std::string text) {
    
}

Worked examples

CallResult
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;
}

The same problem in another language

More validation problems in C++