当char代替int时,避免无限循环 [英] Avoiding infinite loop when a char is enter in place of int

查看:238
本文介绍了当char代替int时,避免无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个银行系统项目,需要确保每个输入都是有效的(程序必须是健壮的)。

但是当我有一个 int 类型的变量时,用户输入 char 键入一个无限循环。

例如:

I'm doing a Banking System project and need to make sure that every input is valid(program has to be robust). If invalid input is given then user has to enter again.
But when i have a variable of int type and user enters char type an infinite loop begins.
For example:

int i;
cin>>i;

如果用户输入 char 。我如何避免它,并再次要求用户输入?

感谢

If user enters a char infinite loop starts. How can i avoid it and ask user for an input again?
Thanks

推荐答案

这可能有帮助;首先写入 std :: string ,然后遍历字符串中的所有元素,检查它们是否为数字。使用标头< cctype> for isdigit()< cstdlib>对于std :: atoi ,虽然在c ++ 11你可以使用 std :: stoi 如果你的编译器支持它。

Here is another approach that might help; first writing to std::string and then going over all elements in the string checking if they're digit. Using header <cctype> for isdigit() and <cstdlib> for std::atoi, although in c++11 you can use std::stoi if your compiler supports it.

如果您写: 141.4123 ,转换后的结果将是 141 (如果您让用户输入'。'

If you write: 141.4123, the result will be 141 after converting (if you let the user type '.'), the result will be truncated because you convert to an 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;
}

这篇关于当char代替int时,避免无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆