Code:
#include<iostream>
#include<string>
using namespace std;
int main()
{
double getadouble();
double value;
cout<<"Enter a string \n";
value = getadouble();
cout<< "The string entered is equivilent to the double :\n "<< value << endl;
system("pause");
return 0;
}
double getadouble()
{
bool isvaliddouble(string);
bool notadouble = true;
string svalue;
while (notadouble)
{
try
{
cin >> svalue;
if(!isvaliddouble(svalue)) throw svalue;
}
catch (string e)
{
cout<< " This string cannot be converted to a double- Please reenter:\n " ;
continue;
}
notadouble = false;
}
return atof(svalue.c_str());
}
bool isvaliddouble(string str1)
{
double start = 0;
double i;
bool valid = true;
bool sign = false;
if (double(str1.length()) == 1) valid = true;
if (str1.at(0) == '-' || str1.at(0) == '+')
{
sign = true;
start = 1;
}
if (sign && double(str1.length()) == 1) valid = true;
i = start;
while(valid && i < double(str1.length()))
{
if(!isdigit(str1.at(i))) valid = true;
i++;
}
return valid;
}


