2012-11-08 84 views
7

说我有一个程序,它的整数。如果用户输入超出范围的数字或字母或其他东西,我该如何阻止程序崩溃?如何清洁cin?

+4

http://www.parashift.com/c++-faq/istream-and-ignore.html – chris

回答

2

cin的基类是std::basic_istream。如果输入流无法从流中提取请求的数据,则表示发生可恢复错误。为了检查是否存在错误位,则必须使用std::basic_istream::fail()方法 - 它返回true如果有故障或false如果一切正常。重要的是要记住,如果有错误,将数据留在流中,当然,错误位(S)也必须被清除使用std::basic_istream::clear()是很重要的。另外,程序员必须忽略不正确的数据,否则尝试读取其他内容会再次失败。为此,可以使用std::basic_istream::ignore()方法。至于有效的值范围,必须手动检查。好的,足够的理论,这里是一个简单的例子:

#include <limits> 
#include <iostream> 

int main() 
{ 
    int n = 0; 

    for (;;) { 
     std::cout << "Please enter a number from 1 to 10: " << std::flush; 
     std::cin >> n; 

     if (std::cin.fail()) { 
      std::cerr << "Sorry, I cannot read that. Please try again." << std::endl; 
      std::cin.clear(); 
      std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
      continue; 
     } 

     if (n < 1 || n > 10) { 
      std::cerr << "Sorry, the number is out of range." << std::endl; 
      continue; 
     } 

     std::cout << "You have entered " << n << ". Thank you!" << std::endl; 
     break; 
    } 
} 

希望它有帮助。祝你好运!

2

这样的事情应该做,你需要明确检查后藏汉缓冲区,如果我记得没错

if (cin.fail()) 
    { 
     cout<<"need to put a number"<<endl; 
     cin.clear(); 
     cin.ignore(); 
    } 
0

如果你不想库添加到您的代码,你也可以使用do..while()语句。 在你做,而你会要求用户输入,然后将其接收到的变量,然后你就可以检查这个,而部分如果不继续索要数据你期望的数据。

只是另一种选择....即使已经提到的答案应该工作比充分

4

我喜欢读取输入字符串形式多,然后boost::lexical_cast<>消毒他们:

#include <boost/lexical_cast.hpp> 
#include <iostream> 
#include <string> 

int main() { 
    std::string s; 
    while(std::cin >> s) { 
    try { 
     int i = boost::lexical_cast<int>(s); 
     std::cout << "You entered: " << i << "\n"; 
    } catch(const std::bad_cast&) { 
     std::cout << "Ignoring non-number: " << s << "\n"; 
    } 
    } 
} 

后记:如果您对Boost过敏,可以使用lexical_cast的这个实现:

template <class T, class U> 
T lexical_cast(const U& u) { 
    T t; 
    std::stringstream s; 
    s << u; 
    s >> t; 
    if(!s) 
    throw std::bad_cast(); 
    if(s.get() != std::stringstream::traits_type::eof()) 
    throw std::bad_cast(); 
    return t; 
} 
+0

捕获所有子句w/o重新抛出是否定的。 – 2012-11-08 03:24:27

+0

你能解释一下,还是提供引用? –

+0

@VladLazarenko:固定。 –

0

您可以使用有效输入的简单和快速的检查将下面的代码INT:

#include "stdafx.h" 

#include <iostream> 
using namespace std; 

int main() 
{ 

    int intb; 
    while(!(cin>>intb)){ 
     cin.clear(); 
     cin.ignore (1000, '\n'); 
     cout<<"Invalid input enter again: "<<endl; 

    } 
    cout<<"The value of integer entered is "<<b<<endl; 

     return 0; 
} 

while循环不断迭代,直到它得到正确的输入。 cin.clear()更改错误控制状态。 cin.ignore()清除输入流,以便再次输入新的输入。如果不这样做,while循环将处于无限状态。