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.

30th Nov 2018, 7:24 AM
fuS vid
fuS vid - avatar
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
30th Nov 2018, 8:02 AM
Babak
Babak - avatar
+ 3
C++ Soldier (Babak) Nice! Finally... a fellow regexer đŸ€“!
30th Nov 2018, 8:40 AM
David Carroll
David Carroll - avatar
+ 1
Thanks you, I go for it!
30th Nov 2018, 8:06 AM
fuS vid
fuS vid - avatar