Wednesday, September 1, 2010

Taking input as string 1 - " 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;
}

Reactions:

0 comments:

Post a Comment