tags:

views:

127

answers:

4

How do I make it so that the cin statement only accepts integers?

A: 

Put the cin in a while loop, and test.

cin.exceptions(ios::failbit | ios::badbit );
int a;
bool bGet = true;
while(bGet)
{
  try
  { 
    cin >> a;
    bGet = false;
  }
  catch
  { ; }
}      
Jess
`operator>>` does not throw an exception in this case unless you set a flag with ios::exceptions
Nick Meyer
Like the edit??
Jess
+3  A: 
#include <iostream>
#include <limits>
using namespace std;

int main(){
   int temp;
   cout << "Give value (integer): ";
   while( ! ( cin >> temp ) ){
      cout << "That was not an integer...\nTry again: ";
      cin.clear();
      cin.ignore( numeric_limits<streamsize>::max(), '\n' );
   }
   cout << "Your integer is: " << temp;
}

Found this source from: http://www.dreamincode.net/forums/topic/53355-c-check-if-variable-is-integer/ I needed to do this just yesterday :)

KennyCason
+2  A: 

I don't think you can force std::cin to refuse to accept non-integral input in all cases. You can always write:

std::string s;
std::cin >> s;

since the string doesn't care about the format of the input. However, if you want to test whether reading an integer succeeded you can use the fail() method:

int i;
std::cin >> i;
if (std::cin.fail())
{
   std::cerr << "Input was not an integer!\n";
}

Alternatively, you can just test the cin object itself, which is equivalent.

int i;
if (std::cin >> i)
{
   // Use the input
}
else
{
   std::cerr << "Input was not an integer!\n";
}
Nick Meyer
"I don't think you can do such a thing globally", you can set `cin.exception(ios::failbit)` to apply it globally.
ybungalobill
@ybungalobill Even with the exception mask, you can read other types sucessfully (`std::string s; std::cin >> s;`). To my knowledge, there is no way to force `operator>>` to *always* fail when trying to read a non-integral type (even when the input is in the correct format).
Nick Meyer
Ah, I see how the wording was confusing now. Editing.
Nick Meyer
A: 

Another approach using std::cin.

#include <iostream>
#include <limits>

using namespace std;

int main()
{

    double input;
    while (cin)
    {
        cout << "Type in some numbers and press ENTER when you are done:" << endl;
        cin >> input;
        if (cin)
        {
            cout << "* Bingo!\n" << endl;
        }
        else if (cin.fail() && !(cin.eof() || cin.bad()))
        {
            cout << "* Sorry, but that is not a number.\n" << endl;
            cin.clear();
            cin.ignore(numeric_limits<std::streamsize>::max(),'\n');
        }
    }
}

g++ -o num num.cpp

karlphillip