Golgappa.net | Golgappa.org | BagIndia.net | BodyIndia.Com | CabIndia.net | CarsBikes.net | CarsBikes.org | CashIndia.net | ConsumerIndia.net | CookingIndia.net | DataIndia.net | DealIndia.net | EmailIndia.net | FirstTablet.com | FirstTourist.com | ForsaleIndia.net | IndiaBody.Com | IndiaCab.net | IndiaCash.net | IndiaModel.net | KidForum.net | OfficeIndia.net | PaysIndia.com | RestaurantIndia.net | RestaurantsIndia.net | SaleForum.net | SellForum.net | SoldIndia.com | StarIndia.net | TomatoCab.com | TomatoCabs.com | TownIndia.com
Interested to Buy Any Domain ? << Click Here >> for more details...

Write an implementation of “float stringToFloat(char *str).”
The code should be simple, and not require more than the
basic operators (if, for, math operators, etc.).
• Assumptions
• Don’t worry about overflow or underflow
• Stop at the 1st invalid character and return the number
you have converted till then, if the 1st character is
invalid return 0
• Don’t worry about exponential (e.g. 1e10), instead you
should treat ‘e’ as an invalid character
• Write it like real code, e.g. do error checking
• Go though the string only once
• Examples
• “1.23” should return 1.23
• “1a” should return 1
• “a”should return 0

Answer Posted / piyush sharma

#include<iostream>

using namespace std;

int main()
{
char* str = "36.78sg67";
char ch;
int decimal_pt = 0;
int dec_count = 0;
float val = 0.0;

for( int i=0; str[i]!='\0'; i++ )
{
ch = str[i];
if( ch == '.' )
{
decimal_pt = 1;
continue;
}

if( !(ch>=48 && ch<=57) )
break;

val = val*10 + ch-48;
if( decimal_pt == 1 )
dec_count++;

}

for( int i=0; i<dec_count; i++ )
val = val/10;

cout << val << endl;
system("pause");
return 0;
}

Is This Answer Correct ?    3 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Hello. How to write a C program to check and display president party like if i type in the console "biden" and hit enter the output shoud be : "biden is democrat" and if i type "trump" and hit enter the output shoud be: "trump is republican"

2046


Which is more efficient, a switch statement or an if else chain?

981


ATM machine and railway reservation class/object diagram

5203


What 'lex' does?

1112


What is the difference between NULL and NUL?

1255


Can a pointer point to null?

1036


Where static variables are stored in memory in c?

963


Write a program to swap two numbers without using a temporary variable?

1091


What is difference between structure and union in c?

938


What are qualifiers and modifiers c?

956


Why do we use & in c?

958


How do you list a file’s date and time?

1036


define string ?

1063


What are derived data types in c?

1023


cavium networks written test pattern ..

4038