c++ - 在 C++ 中检查合法的整数输入

标签 c++ error-handling integer error-checking

所以我看到很多人问这个问题,但网络上并没有很多可靠的答案。大多数只是检查一个整数是否被放置在一个字符串的位置,但是如果输入了一个 float ,那么它会截断下半部分,或者如果插入了整数和字符,它会截断字符。我需要帮助编写一段代码来检查用户输入并要求用户重试他的输入是否无效或有效/无效的组合。我认为基本的想法是制作一个字符串,这样它就可以接受任何东西,然后使用 sstream 进行操作,如果输入是合法的,然后返回到 int,但我无法真正设法检查其他部分。如果有人遇到这个或者可以帮助我,请将我链接到它。当我清楚地知道要做什么时,我会发布我的代码。

最佳答案

假设您不能使用boost::lexical_cast,您可以编写自己的版本:

#include <sstream>
#include <iostream>
#include <stdexcept>
#include <cstdlib>
template <class T1, class T2>
T1 lexical_cast(const T2& t2)
{
  std::stringstream s;
  s << t2;
  T1 t1;
  if(s >> std::noskipws >> t1 && s.eof()) {
    // it worked, return result
    return t1;
  } else {
    // It failed, do something else:
    // maybe throw an exception:
    throw std::runtime_error("bad conversion");
    // maybe return zero:
    return T1();
    // maybe do something drastic:
    exit(1);
  }
}



int main() {
  std::string smin, smax;
  int imin, imax;

  while(std::cout << "Enter min and max: " && std::cin >> smin >> smax) {
    try {
      imin = lexical_cast<int>(smin);
      imax = lexical_cast<int>(smax);
      break;
    } catch(std::runtime_error&) {
      std::cout << "Try again: ";
      continue;
    }
  }

  if(std::cin) {
    std::cout << "Thanks!\n";
  } else {
    std::cout << "Sorry. Goodbye\n";
    exit(1);
  }
}

关于c++ - 在 C++ 中检查合法的整数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15275097/

相关文章:

python - 愚蠢的例子但类型错误?

php - Laravel SQLSTATE[HY000] : General error: 1615 Prepared statement needs to be re-prepared

c++ - 命名管道读取超时

c++ - Allegro 5绘图缓冲

python - 在重复输入时退出Python MySQLdb

javascript - 如何在函数中输入每三位分隔的数字

python - 如何打印前面有一定数量空格的整数?

java - 如何将元素(或将 Integer ArrayList 转换)添加到 Integer Array

c++ - 在 while 循环中接受用户输入

c++ - 使用 std::tm 作为 std::map 中的键