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

 

Integer to String

Converts a given integer to a string.
Code
inttostring.zip
File Size: 4216 kb
File Type: zip
Download File

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

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

void IntToStr (int num, char str[])
{
int Begin, End, SizeOfnum;
SizeOfnum = NumOfCharacters(num); // returns how many characters long

// If number is negative, then shift start position + 1 to ignore -, copy - to array, Make integer positive
if (num < 0)
{str[0] = '-'; num *= -1; Begin = 1;}

str[SizeOfnum] = '%%CONTENT%%'; 
End = SizeOfnum - 1;

while (End >= Begin)
{
str[End--] = (num%10)+ '0';
num = (num/10);
}
}

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

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

void main()
{
int x;
wcout <<  endl << "*** This module converts integer to string and  then again from string to an integer ***" << endl;
wcout << "*************************************************" << endl;
cout << endl << StrToIntPTR("-137") << " - Size = " << NumOfCharacters(137) << endl;
char* f = new char[NumOfCharacters(137)];
IntToStr(-137, f);
cout << "Converted -137 to " << f << endl;
cin >> x;
 }