当char进入而不是int时,避免无限循环

时间:2014-11-28 14:04:47

标签: c++ infinite-loop cin

我正在做一个银行系统项目,需要确保每个输入都是有效的(程序必须是健壮的)。如果给出无效输入,则用户必须再次输入 但是当我有int类型的变量并且用户输入char类型时,会开始无限循环 例如:

int i;
cin>>i;

如果用户输入char无限循环启动。如何避免它并再次要求用户输入? 感谢

2 个答案:

答案 0 :(得分:3)

无限循环的原因:

cin进入失败状态,这使得它忽略了对它的进一步调用,直到错误标志和缓冲区被重置。

cin.clear();
cin.ignore(100, '\n'); //100 --> asks cin to discard 100 characters from the input stream.

检查输入是否为数字:

在你的代码中,即使是非int类型也会被转换为int。无法检查输入是否为数字,无需将输入输入到char数组中,并且在每个数字上调用isdigit()函数。

函数isdigit()可用于分辨数字和字母。此功能出现在标题中。

is_int()函数看起来像这样。

for(int i=0; char[i]!='\0';i++){
   if(!isdigit(str[i]))
      return false;
}
return true;

答案 1 :(得分:2)

这是另一种可能有用的方法;首先写入std::string,然后检查字符串中的所有元素,检查它们是否已重新编号。使用标头<cctype> for isdigit()<cstdlib> for std::atoi,尽管在c ++ 11中,如果您的编译器支持它,您可以使用std::stoi

如果您编写: 141.4123 ,转换后结果将为 141 (如果您让用户输入&#39;。&#39;),结果将被截断,因为您转换为int。

工作示例:

int str_check(string& holder, int& x)
{
  bool all_digits = true; // we expect that all be digits.

  if (cin >> holder) {
    for(const auto& i : holder) {
      if (!isdigit(i) && i != '.') { // '.' will also pass the test.
        all_digits = false;
        break;
      }
    }
    if (all_digits) {
      x = atoi(holder.c_str()); // convert str to int using std::atoi
      return 1;
    }
    else
      return 0;
  }
}

int main()
{
  int x{};
  string holder{};
  while (1)
  {
    if (str_check(holder, x))
      cout << x << '\n';
  }

  return 0;
}