SHARE
TWEET

Untitled

a guest Apr 22nd, 2019 73 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <stdio.h>
  2. #include "limits.h"
  3.  
  4. int parse_string(const char *input) {
  5.     int result = 0;
  6.     if(input == nullptr) {
  7.         // null-string
  8.         return 0;
  9.     }
  10.  
  11.     int idx = 0;
  12.     // loop until we encounter zero-terminator
  13.     while(input[idx] != 0) {
  14.         if(input[idx] < '0' || input[idx] > '9') {
  15.             // invalid character
  16.             break;
  17.         }
  18.         int digit = int(input[idx] - '0'); // 0 <= digit <= 9
  19.         if(result > INT_MAX / 10) { return 0; } // mult overflow
  20.         result *= 10;
  21.         if(result > INT_MAX - digit) { return 0; } // add overflow
  22.         result += digit;
  23.         idx++;
  24.     }
  25.     return result;
  26. }
  27.  
  28. int main(int argc, char ** argv) {
  29.     printf("%d", INT_MAX);
  30.     printf("%d", parse_string("2147483647"));
  31. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top