+ 1

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.

6th Jul 2018, 7:37 AM
Deep Patel
Deep Patel - avatar
6 Answers
+ 1
You 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";
6th Jul 2018, 7:48 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
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;
6th Jul 2018, 8:27 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 1
Deep@Code i recommend using code::blocks instead of dev-c++, it's more up-to-standard
6th Jul 2018, 11:53 AM
hinanawi
hinanawi - avatar
0
Dev C++ is giving me error while including the library #include <regex>
6th Jul 2018, 8:25 AM
Deep Patel
Deep Patel - avatar
0
Output was 199711 @Kinshuk vasisht
6th Jul 2018, 10:26 AM
Deep Patel
Deep Patel - avatar
0
Deep@Code 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.
6th Jul 2018, 12:33 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar