Learn Computer Science programming - C# and C++ Algorithms

 

Integer to String

Converts an integer into a string. The conversion is don using three methods below. The first uses array variables and the second uses pointers. The third uses a while loop. 
Code
stringtoint.zip
File Size: 2468 kb
File Type: zip
Download File

#include <iostream>
#include <string.h>
#include <windows.h>
using namespace std;

int Power (int number, int power)
{
int counter = 0; 
int result = 1;
while (counter++ < power)
result = result * number;
return result;
}

int NumOfCharacters(int x)
{
int Size=0;
if (x < 0) // Add 1 for negative value
{
Size = 1; x *= -1;
}
while (x) // Divide X by 10 and increase size
{
x = x/10; Size++;
}
return Size;
}

int StrToInt(char * a)
{
int StartLocation = 0;
int Sign = 1;
int Length = strlen (a) -1;
int P = Power (10,(Length - StartLocation));;
int Num = 0;

if (a[0] == '-')
{
StartLocation = 1;
Sign = -1;
Length--;
P = Power (10,(Length - StartLocation));
}

while (StartLocation <= Length)
{
Num += (a[StartLocation] - '0') * P;
StartLocation++;
P = Power (10,(Length - StartLocation));
}
return (Num * Sign);
}

int StrToIntPTR(char * a)
{
int Sign = 1; int power = 1; int Num = 0;
char *pBegin = &a[0];
char *pEnd = &a[strlen (a)];


if (*pBegin == '-')
{
pBegin++;
Sign = -1;
}

while (pEnd - pBegin)
{
power = Power (10, (pEnd - pBegin -1));
Num = Num + ((*pBegin) - '0') * power;
pBegin++;
}
return (Num * Sign);
}

int StrToInt3(char* a)
{
int Start=0, Sign = 1, RT=strlen(a)-1;
int End = RT;
int power = End-RT;
int temp, x = 0;
if (a[0] == '-')
{
Start = 1;
Sign = -1;
}
while (RT>=Start)
{
power = End-RT;
temp = ((a[RT]) - '0');
while(power)
{
temp *= 10 ;
power--;
}
x += temp;
RT--;
}
return (x*Sign);
}

void main()
{
int x;
wcout <<  endl << "*** This module converts a string to an Integer ***" << endl;
wcout << "*************************************************" << endl;
char *string1 = "12345";
char *string2 = "67890";
char *string3 = "1112131415";
cout << endl << StrToIntPTR(string1) << endl;
cout << endl << StrToInt3(string2) << endl;
cout << endl << StrToInt(string3) << endl;
cin >> x;
 }