Search code examples
c++error-handlingconditional-statementsstrtol

Checking string to int error without loops/conditionals


I'm doing a problem on HR and cant figure out how to check for error without using conditional statements. How is this done in C++?

// if string is int output it, else output "Bad string"
// need to do this without any loops/conditionals
int main(){
    string S;
    char *end;
    long x;
    cin >> S;
    const char *cstr = S.c_str();
    x = strtol(cstr,&end,10);

    if (*end == '\0')
        cout << x;
    else
        cout << "Bad string";

    return 0;
}

Should I be using something besides strtol?


Solution

  • stoi is indeed what you'll want to use.

    Given an input in string S one possible way to handle it would be:

    try {
        cout << stoi(S) << " is a number\n";
    } catch(const invalid_argument& /*e*/) {
        cout << S << " is not a number\n";
    }
    

    Live Example

    The violation here is that stoi is only required to cosume the leading numeric part of the string not ensure that the entire string is an int. So "t3st" will fail cause it's not led by a number, but "7est" will succeed returning a 7. There are a handful of ways to ensure that the entire string is consumed, but they all require an if-check.