Read an int from user - C++ File Stream

C++ examples for File Stream:cin

Description

Read an int from user

Demo Code

#include <iostream>
#include <string>
using namespace std;
int getanInt();  // function declaration (prototype)
int main()/*  w w  w  .  j  ava  2s  .  com*/
{
   int value;
   cout << "Enter an integer value: ";
   value = getanInt();
   cout << "The integer entered is: " << value << endl;
   return 0;
}
int getanInt()
{
   bool isvalidInt(string);  // function declaration (prototype)
   bool notanint = true;
   string svalue;
   while (notanint)
   {
      try
      {
         cin  >> svalue;  // accept a string input
         if (!isvalidInt(svalue)) throw svalue;
      }
      catch(string e)
      {
         cout << "Invalid integer - Please reenter: ";
         continue;  // send control to the while statement
      }
      notanint = false;
   }
   return atoi(svalue.c_str());  // convert to an integer
}
bool isvalidInt(string str)
{
   int start = 0;
   int i;
   bool valid = true;  // assume a valid integer
   bool sign = false;  // assume no sign
   if (int(str.length()) == 0) valid = false;
   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