My program always comes back as true, instead of requiring only 1 decimal point.
ID: 3589983 • Letter: M
Question
My program always comes back as true, instead of requiring only 1 decimal point. I can't figure out why. Help?
9. (Useful utility) a. Write a C++ function named isvalidreal) that checks for a valid dou ble-precision number. This kind of number can have an optional + or - sign, at most one decimal point (which can be the first character), and at least one digit between 0 and 9. The function should return a Boolean value of true if the entered number is a real number; other- wise, it should return a Boolean value of false.Explanation / Answer
Everything is well and good except one thing:
you have checked for the presence of "." but do not store it anywhere. Anyway, i have modified your code, go through it, run it nad check it with al the possible cases.if there will be any problem, please rply us.
Thank you.
My program:
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
int main()
{
bool isValidReal(string);
string value;
double number;
cout<<"enter the value: ";
cin>>value;
if(!isValidReal(value))
{
cout<<"number is not real ";
}
else
{
number=atof(value.c_str());
cout<<"the number you entered is"<<number;
}
system("pause");
return 0;
}
bool isValidReal(string str)
{ int count_point=0;
int start=0,i;
bool valid=true;
bool sign=false;
bool have_point=false;
if(int(str.length())==0)
{
valid=false;
}
if(str.at(0)=='-'||str.at(0)=='+')
{
sign=true;
start=1;
}
if(sign&&int((str.length())==1))
valid=false;
i=start;
while(valid&& i< int(str.length()))
{
if(!isdigit(str.at(i)))
valid=false;
if(str.at(i)=='.')
{
have_point=true;
count_point++;
valid=true;
}
i++;
}
if(have_point&&valid&&count_point==1)
return true;
else
return false;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.