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;
}

How compact should your code be?

A shorter, but perhaps less readable, version can replace the last three statements to return the correct bool value. Recent compilers should produce equivalently efficient code, so the most important thing is to choose the most readable version. In general try to resist making programs shorter without improving their clarity. The following is plausible, and may be more readable.

   return *digit == 0;   // true if at end of string.

A more extreme shortening is definitely NOT more readable.

bool s2i(char*d,int&r){for(r=0;*d>='0'&&*d<='9';r=r*10+*(d++)-'0');return*d==0;}

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. Add a range check. Perhaps the simplest way to do this is to convert it into a double, then check the range of the double.

Solution: See Solution: C-string to double for a solution to some of these exercises.