C++ 用户输入验证

在编写程序时,请考虑用户将如何滥用您的程序,尤其是在文本输入方面。对于每个文本输入点,请考虑:

  • 会不会提取失败?
  • 用户可以输入比预期更多的输入吗?
  • 用户可以输入无意义的输入吗
  • 用户可以溢出输入吗?

以下代码将清除任何无关的输入:

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

以下代码将测试并修复失败的提取或溢出:

if (!std::cin) // has a previous extraction failed or overflowed?
{
    // yep, so let's handle the failure
    std::cin.clear(); // put us back in 'normal' operation mode
    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // and remove the bad input
}

最后,如果原始输入无效,则使用循环要求用户重新输入。

posted @ 2023-02-16 14:26  Leafmoes  阅读(15)  评论(0编辑  收藏  举报