The value data type is Float
. Here I need to validate the value if it is only numbers(int,float) not a string
or special character
.
Ex: value = 123df.125
How to check value if a string is mixed.
Here I need to display a warning message "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:
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:
#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;
}
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.