Advertisement
SumitParakh

String to long float

Sep 8th, 2012
187
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.87 KB | None | 0 0
  1. // StrToFloat.cpp : main project file.
  2.  
  3. #include "stdafx.h"
  4. #include<iostream>
  5. #include<string.h>
  6. #include<math.h>
  7. using namespace std;
  8.  
  9. void conversion(long float &convert,char str[])//It is used to convert string into long float(eg--"1.2"=1.2)
  10. {
  11.     int i=0;
  12.     int dot=0,pw=1;
  13.     while(str[i]!='\0')
  14.     {
  15.         if(str[i]=='.')
  16.         {
  17.             convert=convert*1.0;           
  18.             dot=1;
  19.             i++;
  20.         }
  21.         else
  22.         {
  23.             if(dot==0)
  24.                 convert=convert*10+str[i++]-48;        
  25.             else
  26.                 convert=convert+pow(1/10.0,pw++)*(str[i++]-48);
  27.         }
  28.     }
  29. }
  30. void validation(char str[],int &id)//2 check the validation and c if it is alphabetic string or float string
  31. {
  32.     for(int i=0;i<strlen(str);i++)
  33.     {
  34.         if(isalpha(str[i]))
  35.         {
  36.             id=1;
  37.             break;
  38.         }
  39.     }
  40. }
  41. int main()
  42. {
  43.     char str[20];
  44.     cout<<"Please enter first string : ";
  45.     cin.getline(str,20,'\n');
  46.     int id=0,i;
  47.     validation(str,id);
  48.     if(id==1)
  49.     {
  50.             cout<<"Sorry, it is not convertible to a long float number.\nPlease enter a valid input..";
  51.             cout<<"\nPress any key to exit..";
  52.             cin.get();
  53.             exit(1);
  54.     }
  55.     else
  56.     {
  57.         cout<<"Congrats!!! You entered a valid input "<<char(1);
  58.         long float convert=0.0;
  59.         conversion(convert,str);
  60.         cout<<"\nAfter converting, the long float number is : "<<convert<<"\n";
  61.         long float convert1=0.0;
  62.         cout<<"\n\nNow, Please enter second string : ";
  63.         cin.getline(str,20,'\n');
  64.         id=0;
  65.         validation(str,id);
  66.         if(id==1)
  67.         {
  68.             cout<<"Sorry, it is not convertible to a long float number.\nPlease enter a valid value..";
  69.             cout<<"\nPress any key to exit..";
  70.             cin.get();
  71.             exit(1);
  72.         }
  73.         else
  74.         {
  75.             long float convert1=0.0;
  76.             cout<<"Congrats!!! You entered a valid input "<<char(1);
  77.             conversion(convert1,str);
  78.             cout<<"\nAfter converting, the long float number is : "<<convert1<<"\n";
  79.             cout<<"\n\nAfter multiplication, the result is : "<<convert*convert1<<"\n\n\n";
  80.         }
  81.     }
  82.     return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement