【发布时间】: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