Ad

Chapter - 4: Functions

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


Ad
C
Sections
5
Exercises
#include<iostream>
#include<conio.h>

using namespace std;

int astn(char *, int = 0);
double astn(char *, double = 0.0);

int main()
{
	double num = 0;
	num = astn("123.33", num);
	cout << num << endl;
	int n = astn("12333", 0);
	cout << n << endl;
	return 0;
}

int astn(char * str, int num)
{
	int tempNum = 0;

	for (int i = 0; str[i] != '\0'; i++)
		if (isdigit(str[i]))
			tempNum = tempNum * 10 + (str[i] - 48);

	num = tempNum;

	return num;
}

double astn(char * str, double num)
{
	double tempNum = 0;
	int i;
	for (i = 0; str[i] != '\0'; i++)
	{
		if (isdigit(str[i]))
			tempNum = tempNum * 10 + (str[i] - 48);
		else if (str[i] == ',');
		else if (str[i] == '.')
			break;
	}
	for (int j = 1; str[i] != '\0'; i++, j *= 10)
	{
		if (isdigit(str[i]))
			tempNum = tempNum + (float(str[i] - 48) / j);
	}

	num = tempNum;
	return num;
}
Ad

© 2024 Garbage Valuegarbage value logo