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
2010-09-29 19:07:55
`operator>>` does not throw an exception in this case unless you set a flag with ios::exceptions
Nick Meyer
2010-09-29 19:17:21
Like the edit??
Jess
2010-09-30 04:23:41
+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
2010-09-29 19:10:36
+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
2010-09-29 19:11:02
"I don't think you can do such a thing globally", you can set `cin.exception(ios::failbit)` to apply it globally.
ybungalobill
2010-09-29 19:18:01
@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
2010-09-29 19:25:21
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
2010-09-29 19:32:11