Software & Finance





Visual C++ - String to Number Conversion Program





Here is the Visual C++ source code for string to number conversion.

 

First the length of the string is identified. To handle the negative numbers, the first character is being checked for '-'. If it is '-', then negative number indication flag is set to true (1).

 

The next character ascii value is being deducted from character '0' to get the numeric value. If it is in between 0-9, then it will be stored into the result and when the subsequent character is getting in, the previous value is multiplied by 10. otherwise a non numeric character is found and the return value would be zero.

 

Example String: 5647

Result Value

1st Iteration: 5

2nd Iteration: 5 * 10 + 6 = 56

3rd Iteration: 56 * 10 + 5 = 564

4th Iteration: 564 * 10 + 7 = 5647



Source Code


#include <stdio.h>

#include <iostream>

#include <tchar.h>

 

 

int StringToNumber(const char *buffer)

{

   int result = 0;

   int startIndex = 0;

   bool negativeNumber = false;

   if(buffer[0] == '-')

   {

         negativeNumber = true;

         startIndex = 1;

   }

   for(int i = startIndex; i < strlen(buffer); i++)

   {

      if(buffer[i] >= '0' && buffer[i] <= '9')

      {

         int digit = buffer[i] - '0';

         result = result * 10 + digit;

      }

      else

         return 0;

   }

   if(negativeNumber == true)

      result *= -1;

   return result;

}

 

 

int _tmain(int argc, _TCHAR* argv[])

{

   char buffer[128];

  

   std::cout << "String to Number Conversion Program\n";

 

   while(1)

   {

      std::cout << "Enter a String (-1 to exit): ";

      std::cin >> buffer;

     

      int number = StringToNumber(buffer);

 

      std::cout << "Converted Number: " << number << "\n";

 

      if(number == -1)

         break;

   }

      return 0;

}

 

Output