try catch does not work for std::stoull c++

mcyrill

std::stoull() does not throw any exception for definitely incorrect input.

Example of code, where this problem occurs:

#include <iostream>
#include <exception>
#include <string>
#include <sstream>

using namespace std;

int main() {
    stringstream ss("6yh45gu94j5vun:");
    string valueStr;
    if (!getline(ss, valueStr, ':')) {
        return -1;
    }
    unsigned long long value;
    try {
        value = stoull(valueStr, nullptr, 16);
    } catch (exception& e) {
        cout << -1;
        return -1;
    }
    cout << value;
}

I tried to catch every single exception, but still doesn't work.

Can you help me?

Andreas Wenzel

The function std::stoull does not throw an exception because it successfully converted the input to the integer 6. It will stop reading once it encounters a character it cannot convert. If at least one character was converted, then the conversion is considered successful.

If you want to determine how much of the input it converted, you must use the second parameter of std::stoull, instead of setting it to nullptr.

In order to use the second parameter, you must define an additional variable

std::size_t num_chars_converted;

and then call the function like this:

value = std::stoull(valueStr, &num_chars_converted, 16);

If no exception is thrown, then the variable num_chars_converted will contain the number of characters converted. You can then compare that value with the length of the string, in order to determine whether the entire string was converted.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related