Tuesday 24 June 2014

C++ program to convert string to float

Here I given four four programs to convert string to float. First method simply use atof function to convert string to float, second method does the same without using atof function and method third and fourth convert string to float using function and recursion.


Method 1 : C++ program to convert string to float using atof() function
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    char str[100];
    float n;
    cout<<"Enter string : ";
    cin>>str;
    n=atof(str);
    cout<<"After converting to integer : "<<n;
    return 0;
}


Method 2 : C++ program to convert string to float without using atof() function
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
int main()
{
    char str[20];
    int i;
    float n=0,temp=.1;
    cout<<"Enter string ";
    cin>>str;
    for(i=0;str[i]!='.';i++)
    {
        if(str[i]==0)
        {
            cout<<"After converting to float "<<n;
            return 0;
        }
        n=n*10+(str[i]-48);
    }
    for(int y=i+1;str[y]!='\0';y++)
    {
        n+=(str[y]-48)*temp;
        temp/=10;
    }
    cout<<"After converting to float "<<n;
    return 0;
}



Method 3 : C++ program to convert string to float using function
#include<iostream>
#include<math.h>
#include<string.h>
using namespace std;
float convert(char *str)
{
    int i;
    float n=0,temp=.1;
    for(i=0;str[i]!='.';i++)
    {
        if(str[i]==0)
            return n;
        n=n*10+(str[i]-48);
    }
    for(int y=i+1;str[y]!='\0';y++)
    {
        n+=(str[y]-48)*temp;
        temp/=10;
    }
    return n;
}
int main()
{
    char str[10];
    cout<<"Enter string ";
    cin>>str;
    cout<<"After converting to float "<<convert(str);
    return 0;
}





Method 4 : C++ program to convert string to float using recursion
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
void convert2(char *str,float &n,int i,float temp)
{
    if(str[i]==0)
        return ;
    n=n+(str[i]-48)*temp;
    convert2(str,n,i+1,temp/10);
}
void convert1(char *str,float &n,int i)
{
    if(str[i]=='\0')
        return ;
    else if(str[i]=='.')
    {
       convert2(str,n,i+1,.1);
       return ;
    }
    n=n*10+(str[i]-48);
    convert1(str,n,i+1);
}
int main()
{
    char str[20];
    float n;
    cout<<"Enter string ";
    cin>>str;
    convert1(str,n,0);
    cout<<"After converting to float "<<n;
    return 0;
}




No comments:

Post a Comment