Ad

Chapter - 4: Functions

Write an overloaded function to convert an int to an ASCII string and to convert a float to an ASCII string.


Ad
C
Sections
4
Exercises
#include<iostream>
#include<conio.h>
#include<cstdlib>
#include<string>

using namespace std;

char * ntas(char *, int);
char * ntas(char *, double);

int main()
{
	char str1[20], str2[20];
	ntas(&str1[0], 231.324);
	cout << str1 << endl;
	return 0;
}

char * ntas(char *str, int num)
{
	int i;
	for (i = 0; num; i++)
	{
		str[i] = num % 10 + 48;
		num /= 10;
	}
	str[i] = '\0';//Terminating the string

	_strrev(str); /*As the numbers saved in the string are reverse of original number
	So we will reverse it back to make it like original.*/
	return str;
}

char * ntas(char * str, double num)
{	
	int Lint, i;
	char lstr[20], rstr[20];
	long long Rint;
	double fractional;

	Lint = int(num);
	fractional = num - Lint;
	// Separating the integer and fractional part of the real number


	Rint = fractional * 10000000000;
	while (Rint % 10 == 0)
		Rint /= 10;
	//Making fractional part, like integer


	//storing integer part in lstr;
	for (i = 0; Lint; i++)
	{
		lstr[i] = Lint % 10 + 48;
		Lint /= 10;
	}
	lstr[i] = '\0';
	_strrev(lstr);
	//putting a decimal after integer part.
	strcat(lstr, "."); 

	
	//Storing fractional part in rstr.
	for (i = 0; Rint; i++)
	{
		rstr[i] = Rint % 10 + 48;
		Rint /= 10;
	}
	rstr[i] = '\0';
	_strrev(rstr);


	//Joining lstr to rstr and storing in str.
	strcat(lstr, rstr);
	strcpy(str, lstr);

	return str;
}
Ad

© 2024 Garbage Valuegarbage value logo