我该如何消毒cin?

时间:2012-11-08 02:47:12

标签: c++

假设我有一个接受整数的程序。如果用户输入超出范围的号码或字母或其他内容,如何阻止程序崩溃?

6 个答案:

答案 0 :(得分: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";
    }
  }
}

Postscript :如果你对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;
}

答案 1 :(得分:3)

这样的事情你应该在检查后清除缓冲区,以及我是否记得正确

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

答案 2 :(得分:3)

cin的基类是std::basic_istream。如果输入流无法从流中提取请求的数据,则表示可恢复的错误。为了检查该错误位,必须使用std::basic_istream::fail()方法 - 如果发生故障则返回true或如果一切正常则返回false。重要的是要记住,如果有错误,数据将保留在流中,当然,还必须使用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;
    }
}

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

答案 3 :(得分:1)

您可以使用cin.good()cin.fail()检查阅读是否成功。

请参阅User Input of Integers - Error Handling

答案 4 :(得分:0)

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

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

答案 5 :(得分: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循环将处于无限状态。