简体   繁体   English

在VC ++ Float数据类型值中,如何检查字符串或特殊字符是否未混合

[英]In VC++ Float data type value, how do you check if string or special characters are not mixed

The value data type is Float . 值数据类型为Float Here I need to validate the value if it is only numbers(int,float) not a string or special character . 在这里,如果只有数字(int,float)而不是stringspecial character ,则需要验证该值。

Ex: value = 123df.125 例如:值= 123df.125

How to check value if a string is mixed. 如何检查字符串是否混合的值。

Here I need to display a warning message "the value is not proper" . 在这里,我需要显示一条警告消息"the value is not proper"

You may want to try this if you have given a string. 如果您提供了一个字符串,您可能想尝试一下。

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);
}

If you are getting the data from user input (The cli or a file, for example), you could check if the read operation fails: 如果要从用户输入(例如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;

One more C++11 solution: 另一种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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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