I would like to check if a decimal number adheres to a predefined standard. I have used the following regular expression ^[+-]?[0-9]+(.[0-9]{2,4})$ , but it does not seem to work in C++. I have tried numerous regex verification solutions and it works there as intended. For example if I have the number 0.00000, the output should be false, on the other hand if the number is 0.00, the output should be true. In my case the output just seems not to detect any. This is my source code, can you please help? Thank you.
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: %d\n", detected);
}
UPDATE: The following source code now works as intended:
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: %d\n", 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;
}
Thank you all for helping!