Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling after doing strtol

I am trying to read several numbers on stdin, one number on each line. I want to ignore any trailing text after number and strings if any on any line. To implement this I used the below code:

while (getline(cin, str)) {
    num = strtol(str.c_str(), NULL, 0);

    if (errno != ERANGE && errno != EINVAL) {
        arr[i++] = num;
        req_pages_size++;
        cout << arr[i-1] << "\t";
    }

    str.clear();
}

ISSUE: After unsuccessful conversion, errno doesn't get updated with an error value for successful conversion case. It's value remains the same for previous calls which was unsuccessful.

Please let me know how to handle this issue?

like image 225
neham Avatar asked Nov 17 '25 10:11

neham


1 Answers

The manpage of errno states:

errno is never set to zero by any system call or library function

but you can set it to zero as stated in the manpage of strtol()

the calling program should set errno to 0 before the call, and then determine if an error occurred by checking whether errno has a nonzero value after the call.

so just add

errno = 0;

before calling strtol()

like image 97
mariux Avatar answered Nov 21 '25 10:11

mariux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!