How can we validate input in C++ ?
How can we validate input in C++? Let me elaborate my question: Example I want to show an error saying "Name only contains alphabets" when the user types any number or any other character in the name field.
7/6/2018 7:37:43 AM
Deep Patel
6 Answers
New AnswerYou can use regular expressions in c++ to validate input as per specific criteria. You can learn about regex here : https://www.sololearn.com/learn/9704/?ref=app You need to include the 'regex' header in your code to be able to use regex statements : #include <regex> For your case, the regex will be declared like this : regex pattern("[A-Za-z]+"); Then you can use regex_match for checking if a string satisfies your requirement : string str = "Hello"; if(regex_match(str,pattern)) { cout<<"Good!"; } else cout<<"Try again";
To use the regex library, you need to ensure that your compiler supports c++11 (atleast). Try executing the following statement, and let me know what the output was : cout<<__cplusplus<<endl;
[email protected] i recommend using code::blocks instead of dev-c++, it's more up-to-standard
[email protected] That version is no good in 2018. You need to enable the flag '-std=c++11' for your compiler, or if possible, switch to Code::Blocks 17.12, as hinanawi mentioned.