检测超出整数的实数

时间:2017-03-30 21:59:00

标签: c++

此代码用于检测用户连续输入的字符串中的REAL数字,并将找到的实数作为double值返回。我能够构建它到它检测整数的点,但如果我尝试一个十进制数,它不会检测到它。我认为我的错误在我的isvalidReal()函数中,但我不确定如何移动它以使其工作。

#include <iostream>
#include <string>
#include <cctype>
using namespace std;

int main()
{
double getaReal();  //function prototype
int value;

cout << "Enter a number: ";
value = getaReal();
cout << "the number entered is a real number: " <<value << endl;

return 0;
}





bool isvalidReal(string str)         //function to find real numbers.
{
int start = 0;
int i;
bool valid = true;
bool sign = false;

if (int(str.length()) == 0) valid = false;          //check for empty string
if (str.at(0) == '-' || str.at(0) == '+')            //check for sign
{
    sign = true;
    start = 1;                                   //check for real num at     position 1
}
if (sign && int(str.length()) == 1) valid = false;  //make sure there's atleast 1 char after the sign

i = start;
while (valid && i<int(str.length()))
{
    if (!isdigit(str.at(i))) valid = false;  //found a non-digit character
    i++;                                  // move to next character
}
return valid;
}





double getaReal()
{
bool isvalidReal(string);  //function declaration prototype
bool isnotreal = true;
string input;

while (isnotreal)
{
    try
    {
        cin >> input;     //accepts user input
        if (!isvalidReal(input)) throw input;
    }
    catch (string e)
    {
        cout << "No real number has been detected, continue to\n enter string values: ";
        continue;          //continues user input
    }
    isnotreal = false;
}
return atof(input.c_str());
}

0 个答案:

没有答案