Check if an input is a valid integer - C++ File Stream

C++ examples for File Stream:cin

Description

Check if an input is a valid integer

Demo Code

#include <iostream>
#include <string>
using namespace std;
bool isvalidInt(string);  // function prototype (declaration)
int main()//from w  ww.j  ava2  s  . c  o  m
{
   string value;
   int number;
   cout << "Enter an integer: ";
   getline(cin, value);
   if (!isvalidInt(value))
      cout << "The number you entered is not a valid integer.";
   else
   {
      number = atoi(value.c_str());
      cout << "The integer you entered is " << number;
   }
   return 0;
}
bool isvalidInt(string str)
{
   int start = 0;
   int i;
   bool valid = true;  // assume a valid integer
   bool sign = false;  // assume no sign
   // Check for an empty string
   if (int(str.length()) == 0) valid = false;
   // Check for a leading sign
   if (str.at(0) == '-' || str.at(0) == '+')
   {
      sign = true;
      start = 1;  // start checking for digits after the sign
   }
   if (sign && int(str.length()) == 1)
      valid = false;
   i = start;
   while (valid && i < int(str.length()))
   {
      if (!isdigit(str.at(i)))
         valid = false;  //found a non-digit character
      i++;  // move to next character
   }
   return valid;
}

Result


Related Tutorials