使用正则表达式C++计算数字中的十进制空格



我想检查十进制数是否符合预定义的标准。我使用了以下正则表达式 ^[+-]?[0-9]+(.[0-9]{2,4}($ ,但它似乎在C++中不起作用。我已经尝试了许多正则表达式验证解决方案,它在那里按预期工作。例如,如果我有数字 0.00000,则输出应该是假的,另一方面,如果数字是 0.00,则输出应该是真的。就我而言,输出似乎没有检测到任何输出。这是我的源代码,你能帮忙吗?谢谢。

void detectFormatConsistency()
{
std::regex dbl("^[+-]?[0-9]+(\.[0-9]{2,4})$");
std::smatch matches;
int detected = 0;
for(unsigned int index = 0; index < mixedDistro.size(); index++)
{
double currentValue = mixedDistro[index];
std::string test = std::to_string(currentValue);
if(std::regex_search(test, dbl)) \I also tried with match
{
detected++;
}
}
printf("Number of points detected: %dn", detected);
}

更新:以下源代码现在按预期工作:

void detectFormatConsistency()
{
std::regex dbl("^[+-]?[0-9]+(\.[0-9]{2,4})$");
std::smatch matches;
int detected = 0;
for(unsigned int index = 0; index < mixedDistro.size(); index++)
{
double currentValue = mixedDistro[index];
std::string test = tostring(currentValue);
if(std::regex_match(test, dbl))
{
detected++;
}
}
printf("Number of points detected: %dn", detected);
}

//https://stackoverflow.com/questions/13686482/c11-stdto-stringdouble-no-trailing-zeros     
//Thanks to: @Silencer
template<typename T>
std::string tostring(const T &n) {
std::ostringstream oss;
oss << n;
std::string s =  oss.str();
unsigned int dotpos = s.find_first_of('.');
if(dotpos!=std::string::npos){
unsigned int ipos = s.size()-1;
while(s[ipos]=='0' && ipos>dotpos){
--ipos;
}
s.erase ( ipos + 1, std::string::npos );
}
return s;
}

谢谢大家的帮助!

std::to_string的结果与 printf("%f"( 输出到控制台的字符串相同,后者使用 6 位的默认精度。

因此,您的测试设置不合适,您应该改用字符串数组。

旁注:请注意,在C++中,所有双字母0.00.000.000、...结果是相同的双精度值(即尾随零不相关(。实际上,您始终有 64 位来放置您的值,分布在符号位、指数和尾数上 - 对于所有具有相同指数的值,您始终具有完全相同的精度。有关详细信息,请查看 IEEE 754。

如果你使用字符串,你的方法对我来说看起来很好

bool checkFormatConsistency(const string& d) {
static std::regex dbl("^[+-]?[0-9]+(\.[0-9]{3,4})$");
return std::regex_search(d, dbl);
}
int main() {
vector<string> tests = {
"0.00", "0.000", "0.0000", "0.00000", "10", "10.1", "-1000", "-99.99", "-345.236"
};
for (const string& test : tests) {
cout << test << " -> " << (checkFormatConsistency(test) ? "ok" : "not ok") << endl;
}
return 0;
}

输出:

0.00 -> not ok
0.000 -> ok
0.0000 -> ok
0.00000 -> not ok
10 -> not ok
10.1 -> not ok
-1000 -> not ok
-99.99 -> not ok
-345.236 -> ok

最新更新