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

Explain pointers in c programming?

1066


Which are low level languages?

1046


what is the height of tree if leaf node is at level 3. please explain

2089


What are the advantages of c language?

1045


What is a program flowchart and how does it help in writing a program?

1086


What do you mean by keywords in c?

1086


How can I call a function with an argument list built up at run time?

1175


What is variable and explain rules to declare variable in c?

1020


What is the return type of sizeof?

1029


What is a header file?

1032


Can a function be forced to be inline? Also, give a comparison between inline function and the C macro?

1050


Is array name a pointer?

999


Hai sir, I had planned to write the NIC scientific engineer exam , plz post the sample question......

2136


What is the difference between malloc calloc and realloc in c?

1072


What does the file stdio.h contain?

1001