Question

I'm new to c++ and I am trying to write a code to convert string to float ( I'm not supposed to use atof) but the output of my code is 0 . Please help me to understand what is the problem :

char A[10];
int N[10],c,b=10,a=0,p=0,i;
float s=0.1;
cout<<"reshte ra vared namaeed:";
cin>>A;


for( i=0;A[i]=!'.';i++)
{

a=(a*b)+(A[i]-48);


}


for(A[i]=='.';A[i]!='\0';i++)
{
p=(p*s)+(A[i]-48);


}
cout<<a+p;


getch();
return 0;
Was it helpful?

Solution 2

If the assignment needs you to demonstrate the mathematics you can use something like this:

char A[10];    

int f1=0;
int dot_index=0;

cout << "Enter a floating point number:" << endl;
cin>>A;

for(int i=0; A[i]!='.'; i++)
{            
    f1= ( f1*10 ) + ( A[i]-48 );       
    dot_index=i+1; //we will stop 1 char before '.'
}

float f2=0;
int count=1;

for(int i=dot_index+1;A[i]!='\0';i++)
{
    float temp1 = static_cast<float>(A[i]-48);
    float temp2 = pow(10,count);       
    f2+= temp1/temp2;                
    count++; 
}

float f = f1 + f2;
cout<< " float : " << f1 << "+" << f2 << " = " << f << endl;
printf("\n float %.10f",f);

However I suspect there will be issues with the precision of some of the floating point calculations.

OTHER TIPS

You can use a StringStream.

#include <iostream>
#include <string>
#include <sstream>

You can use it pretty easy. For example:

stringstream sstr;
string s;
float f;
cin >> s; // Get input from stdin
sstr << s; // Copy string into stringstream
sstr >> f; // Copy content of stringstream into float
cout << f << endl; // Output your float

Of course you can put this into a function/template.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top