【问题标题】:C++ function to check if an input is an integer?用于检查输入是否为整数的 C++ 函数?
【发布时间】:2017-01-19 04:22:57
【问题描述】:

我目前正在为学校编写一个 C++ 程序,该程序涉及将输入作为更改的数量,然后告诉用户他们需要多少 25 美分硬币、5 美分硬币和多少便士来进行所述更改。 但是,如果用户输入任何类型的字符或字符串,程序将进入无限循环,无限期地打印我的两三个消息。 有没有我可以使用的功能或其他方法来防止这种情况发生?

编辑:这是我认为代表问题的一些代码

#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cctype>
#include <sstream>
using namespace std;
int main ()
{
        cout << "\nMake Change v0.6.4\n";
        cout << "Type 0 at any time to exit the program.\n";
        char confirmExit;
        int amount;
        while (tolower(confirmExit) != 'y')
        // allows the user to continue using the program with having to type a.out everytime
        // but quit the application at any time with two keystrokes and
        // confirmation so as to not accidentally exit the program
        {
                cout << "\nEnter the amount of change as an integer: ";
                // input total cents to be worked with
                cin >> amount;
                if ((amount)!int)
                {
                        cout << "\nMake sure to type an integer!\n";
                }
                else if (amount == 0)
                {
                        cout << "Are you sure you want to exit the program(y/n)? ";
                        cin >> confirmExit;
                        // confirmation to prevent accidentally exiting out
                }
    cout << "\n";
    return (0);
}

【问题讨论】:

  • 发布您的代码,有人可能会提供帮助。
  • 抱歉,我做了一些修改。
  • 我没有看到任何循环。您演示问题的代码不完整。理想情况下,您应该提供一个示例(在删除与您的问题无关的所有内容之后),可以复制/粘贴、编译和运行以演示问题。
  • 知道了。我想,除了与输入的整数一起工作的部分之外,我已经添加了所有内容。

标签: c++ debugging int infinite-loop


【解决方案1】:

在 C++ 中,一切都是位,可以进行隐式转换以将字符串或其他形式的数据转换为 int 值。您可以在标准库中使用限制头文件并设置输入的最大值和最小值的界限。如果您无法获得它,请在下面评论。我将发布代码。

此链接可能有用- 访问http://lolengine.net/blog/2012/02/08/selectively-restrict-implicit-conversions

【讨论】:

  • 我查找了您提到的头文件(限制)并能够找到解决方案。谢谢!
  • 不用谢我。我们在这里为您提供帮助。请检查我的回答,以便我赢得一些声誉。
【解决方案2】:

查看下面定义的函数:

atoi

strtol

【讨论】:

    猜你喜欢
    • 2016-05-19
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多