0
How can I check if a string contain only floating point or number?
I have to do error handling for my project and I have to check if the string contains only floating point or integer, or may be check if the string don't contains any letters or special characters. Thanks.
3 Answers
+ 8
Use a regex pattern, for example, like this
(-)?\d+(.\d+)?
and check every string input against it like so
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main()
{
string str = "";
cout << "Input string: ";
getline(cin, str);
regex numeric("(-)?\\d+(.\\d+)?");
cout << (regex_match(str, numeric) ? str : "Invalid string!") << endl;
}
_____
https://www.debuggex.com/r/pW15xmR1x-5E73og
+ 3
C++ Soldier (Babak) Nice! Finally... a fellow regexer đ€!
+ 1
Thanks you, I go for it!