简体   繁体   中英

testing for double in visual c++

I am designing a gui in visual c++ and there is a textbox where user inputs values so a calculation can be performed. How do I validate the input to ensure it can be cast to a double value?

In any C++ environment where you have a std::string field and wish to check if it contains a double , you can simply do something like:

#include <sstream>

std::istringstream iss(string_value);
double double_value;
char trailing_junk;
if (iss >> double_value && !(iss >> trailing_junk))
{
    // can use the double...
}

As presented, this will reject things like "1.234q" or "-13 what?" but accept surrounding whitespace eg " 3.9E2 " . If you want to reject whitespace, try #include <iomanip> then if (iss >> std::noskipws >> double_value && iss.peek() == EOF) ... .

You could also do this using old-style C APIs:

double double_value;
if (sscanf(string_value.c_str(), "%lf%*c", &double_value) == 1)

You cannot "cast" a string to a double, you can only convert it. strtod function will return a pointer to the character within the string where the conversion stopped, so you can decide what to do further. So you can use this function for conversion AND checking.

我建议使用Boost的lexical_cast ,如果转换失败,它将抛出异常。

As stated already, strtod(3) is the answer.

bool is_double(const char* str) {
    char *end = 0;
    strtod(str, &end);
    // Is the end point of the double the end of string?
    return end == str + strlen(str);
}

To address @Ian Goldby's concern, if white space at the end of the sting is a concern, then:

bool is_double(const char* str) {
    char *end = 0;
    strtod(str, &end);
    // Is the end point of the double plus white space the end of string?
    return end + strspn(end, " \t\n\r") == str + strlen(str);
}

Since this seems to be a C++ CLI related question and your string from the textbox might be a .NET string, you might want to check the static Double::Parse method. For more portable solutions see the other answers...

Simply convert it to a double value. If it succeeds, the input is valid.

Really, you shouldn't be writing your own rules for deciding what is valid. You'll never get exactly the same rules as the library function that will do the actual conversion.

My favourite recipe is to use sscanf(), and check the return value to ensure exactly one field was converted. For extra credit, use a %n parameter to check that no non-whitespace characters were left over.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM