2

值数据类型是Float。在这里,如果它只是 numbers(int,float) 而不是 a stringor ,我需要验证该值special character

例如:值 = 123df.125

如果字符串混合,如何检查值。

在这里我需要显示一条警告信息"the value is not proper"

4

3 回答 3

1

如果你给了一个字符串,你可能想试试这个。

bool contains_digits (const std::string &str)
{
    return str.find_first_not_of ("0123456789") == std::string::npos;
}

/* C++ 11 */
bool contains_digits(const std::string &str)
{
    return std::all_of (str.begin(), str.end(), ::isdigit);
}
于 2013-10-25T07:33:37.653 回答
0

如果您从用户输入(例如 cli 或文件)获取数据,您可以检查读取操作是否失败:

float f;

if( std::cin >> f )
    std::cout << "OK, a number value was readed" << std::endl;
else
    std::cout << "ERROR: Something that is not a number is at the input, so cin cannot read it as a float" << std::endl;
于 2013-10-25T07:33:15.723 回答
0

另一种 C++11 解决方案:

#include <iostream>
#include <string>
#include <stdexcept>

int main() 
{
    std::string wrong{"123df.125"};
    std::string totallyWrong{"A123"};
    std::string right{"123.125"};
    try
    {
        size_t pos = 0;
        float value = std::stof(right, &pos);
        if(pos == right.size())
            std::cout << "Good value:" << value << "\n";
        else
            std::cout << "Provided value is partly wrong!\n";

        pos = 0;
        value = std::stof(wrong, &pos);
        if(pos == right.size())
            std::cout << "Good value: " << value << "\n";
        else
            std::cout << "Provided value is partly wrong!\n";

        value = std::stof(totallyWrong, &pos);
    }
    catch(std::invalid_argument&)
    {
        std::cout << "Value provided is invalid\n";
    }
    return 0;
}
于 2013-10-25T10:35:02.230 回答