2010-09-29 58 views
0

如何让这个在CIN声明只接受整数?错误在C++处理

+1

究竟你 “只接受整数” 是什么意思?具体而言,如果用户输入其他内容(例如,字母或标点符号),您希望发生什么? – 2010-09-29 19:02:13

+0

http://stackoverflow.com/questions/2292202/while-loop-with-try-catch-fails-at-bad-cin-input – karlphillip 2010-09-29 19:20:55

+0

的'cin'是一个通用的对象,你不能将它修改为只提供整数。你可以修改你的程序只接受整数。可以编写自己的'cin'过滤版本,或者写一些只从文件中取整数并将文件传递给程序的文件。 – 2010-09-29 19:52:26

回答

5

我不认为你可以强制std::cin拒绝接受在所有情况下非整数输入。你可以随时写:

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

因为字符串不关心输入的格式。但是,如果你想测试是否读取整数成功可以使用fail()方法:

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

或者,你可以测试cin对象本身,这是等价的。

int i; 
if (std::cin >> i) 
{ 
    // Use the input 
} 
else 
{ 
    std::cerr << "Input was not an integer!\n"; 
} 
+1

“我不认为你可以做全球这样的事情”,你可以设置'cin.exception(IOS :: failbit)'在全球范围内应用它。 – ybungalobill 2010-09-29 19:18:01

+0

@ybungalobill即使有例外面膜,可以成功地读取其他类型('的std ::字符串s;给std :: cin >> S;')。据我所知,当试图读取非整数类型(即使输入的格式正确)时,也无法强制'operator >>'*总是*失败。 – 2010-09-29 19:25:21

+0

啊,我看到现在的措词是如何混淆了。编辑。 – 2010-09-29 19:27:31

-1

把CIN在while循环和测试。

cin.exceptions(ios::failbit | ios::badbit); 
int a; 
bool bGet = true; 
while(bGet) 
{ 
    try 
    { 
    cin >> a; 
    bGet = false; 
    } 
    catch 
    { ; } 
}  
+0

'运营商>>'除非你设置了具有ios ::例外 – 2010-09-29 19:17:21

+0

像编辑一个标志不扔在这种情况下的例外? – Jess 2010-09-30 04:23:41

4
#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; 
} 

发现这个源来自:http://www.dreamincode.net/forums/topic/53355-c-check-if-variable-is-integer/ 我需要做的这只是昨天:)

0

另一种使用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