C++ Notes: Example: C-String to Int

Converting C-Strings to Integer

If you want to convert a C-string (zero-terminated array of chars) of digits, you can call one of the library functions to do this (good idea), or write something like the following (good exercise).

Character codes for digits

Every character is represented by a pattern of bits. These patterns can be thought of as integers. If your system uses ASCII (or any of the newer standards), the integer value of the code for '0' is 48, '1' is 49, etc. This knowledge is commonly used when converting character digits to their equivalent values.

Example function to convert C-strings to int

One of the problems to solve immediately is what to do with errors. Let's make this a bool function that returns true if we can convert the string (eg, no illegal characters), and false otherwise. We'll pass the value back in a reference parameter.

The code

//============================================== string2int
bool string2int(char* digit, int& result) {
   result = 0;

   //--- Convert each digit char and add into result.
   while (*digit >= '0' && *digit <='9') {
      result = (result * 10) + (*digit - '0');
      digit++;
   }

   //--- Check that there were no non-digits at end.
   if (*digit != 0) {
      return false;
   }

   return true;
}

Exercises

  1. Extend this to take an initial '-' sign for negative numbers. Hint: One way to do this is to check for it at the beginning and set a number to either -1 or 1. Then at the end multiply by this number.
  2. Convert this to convert doubles (string2double(...)). After the integer portion check for a '.'. Then loop over all the remaining digits, multiplying the first by 0.1, the second by 0.01, the third by 0.001, etc. and adding them to the result.
  3. Make sure there is at least one digit.
  4. Write this using arrays, not pointers.
  5. Add range checking by first converting to double using strtod.
  6. Throw an exception instead of returning a boolean.