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

What are header files? What are their uses?

644


What is data type long in c?

627


Write a program to check whether a number is prime or not using c?

580


What is the maximum length of an identifier?

669


Where does the name "C" come from, anyway?

649






What type of function is main ()?

595


What is c value paradox explain?

580


Tell us bitwise shift operators?

604


What is I ++ in c programming?

631


What is the difference between class and object in c?

588


Disadvantages of C language.

664


What does 3 periods mean in texting?

604


What is wrong with this code?

701


How to get string length of given string in c?

611


Is array a primitive data type in c?

584