I want to do validation. I need to make sure that input is an integer. What is the function in C++ that determines that the given input is an integer. And if the input is not an integer then the cin%26gt;%26gt; statement remains there.
Plz guide me with a piece of code eg. lets say the user has to enter his age or marks obtained in a subject.
Validation in C++?
Using atoi() will work - but barely. The truth of the matter is that input is a PITA, especially when it is not some trusted, agreed upon format. Then you need to validate the input properly, which is probably why you are doing this assignment.
In the real world you will rely on insertion operators ("%26gt;%26gt;") less and getline() more. That means learning to parse strings and creating your own library for obvious useful routines. Something like this will be one of many.
#include %26lt;iostream%26gt;
#include %26lt;iomanip%26gt;
using namespace std;
bool isInteger(string s)
{
for (int i = 0; i %26lt; s.length(); ++i)
if (! isdigit(s[i]))
return(false);
return(true);
}
int main()
{
string s;
cin %26gt;%26gt; s;
cout %26lt;%26lt; boolalpha %26lt;%26lt; isInteger(s.c_str()) %26lt;%26lt; endl;
}
Reply:You can always use atoi() CRT function to have it convert it for you. It will return an error if it cannot convert it correctly, then from there you can print whatever you want. Hope this helps!
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment