gpt4 book ai didi

c++ - 如何检查字符串输入是否为有效的 double 值?

转载 作者:太空宇宙 更新时间:2023-11-04 13:04:26 24 4
gpt4 key购买 nike

<分区>

这是我的代码。我正在创建一个接受字符串输入并将其转换为 double 的程序。但是,我需要验证输入是一个有效的 double 值。那我该怎么做呢?例如,3.14 有效,但 3.1.4、bob123 等无效。

namespace validInput
{
bool IsValidDouble(string inputString)
{
int start = 0; // the index we will start looking for digits
bool valid = true; // assume valid for now
int decCount = 0;

// check for an empty string
if (inputString.length() < 1)
{
valid = false; // no need to check anything else
}
// next, check for a leading sign
else if (inputString.at(0) == '-'|| inputString.at(0) == '+')
{
start = 1; // start checking for digits after the sign

// check that there's at least one character after the sign
if (inputString.length() < 2)
{
valid = false; // no need to check anything else
}
}
// *****************************************
// CHECK FOR ONLY ONE DECIMAL IN INPUT
// *****************************************
return valid; // return true if valid, false if not
}

// Taking string, validating, converting to float(decimal)
double TryDoubleInput()
{
double dNumber;
string inputString;

//cin >> inputString; // accept a string input
getline(cin, inputString);
if (!IsValidDouble(inputString))
{
cerr << "Invalid input. Please enter a number: ";
dNumber = TryDoubleInput();
}
else
{
dNumber = atof(inputString.c_str()); // convert to an integer
}
return dNumber;
}
}

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com