try/catch块问题-(0-9)控制台程序之间的整数
Problem with try/catch block - Integer between (0-9) console program
我在运行下面的代码时遇到问题
我所需要做的就是让用户输入一个整数,然后将其保存到我的cNumber变量中。
然后将从cNumber减去CCD_ 1的ASCII值的值分配给变量iNumber,并在try/catch块中对其进行测试。
#include <iostream>
using namespace std;
// Declare variables
char cNumber;
int iNumber;
int main () {
// Begin infinite while loop
while (1) {
// Prompt user to enter aa number within th range of (0-9)
cout << "Please enter an number between 0 and 9: ";
//Get character from the keyboard and validate it as integer
//within the range (0-9)
try {
//Assign user input alue into cNumber variable
cin >> cNumber;
//Subtract ASCII value of zero from cNumber and assign to iNumber
iNumber = cNumber - 48;
if (iNumber < 0) {
throw string(cNumber + " is not within the range of (0-9)");
}
if (iNumber > 9) {
throw string(cNumber + " is not within the range of (0-9)");
}
}
catch (exception ex) {
cerr << cNumber + " is not a valid selection.... Input Error" << endl;
}
cout << "The result is " + iNumber * 2;
}
}
不清楚你在问什么,但我会对你的一些问题进行抨击。
表达式cNumber + " is not within the range of (0-9)"
是char
和char const*
之间的加法,这是无效的。您可能无意中操作了指针地址。
可以将char
连接到字符串,但它必须是实际的std::string
对象。
因此:
throw cNumber + string(" is not within the range of (0-9)");
类似地,您稍后在代码中也会误用+
。
写入:
cerr << cNumber << " is not a valid selection.... Input Error" << endl;
你也投了std::string
,但却接住了std::exception
。字符串不是从异常派生的。阅读C++书中关于try/catch的章节。(无论如何都不建议抛出/捕获字符串,也不建议按值捕获。)
此外,如果输入不是数字,则提取到zero
0中将失败。。。但是在cin
流上没有错误检查/重置。
对于代码的每一行,看看它的每一个组成部分,问问自己,"这是怎么回事?我为什么写这个?"如果对于任何一段代码,你都无法回答并证明这两个问题的答案,停下来思考它是否正确。
您正在抛出一个std::string
,但您的catch块被声明为具有std::exception
参数。
不知道这种不匹配是否是你问题的根源。
在任何情况下,都不建议抛出std::string
,因为此类可以抛出异常,并且如果在处理前一个异常时抛出和异常,则会带来大麻烦(突然终止)。
对我来说似乎过于复杂,为什么不只是:
#include <iostream>
using namespace std;
int main ()
{
// Begin infinite while loop
while (1)
{
// Prompt user to enter aa number within th range of (0-9)
cout << "Please enter an number between 0 and 9: ";
// Get character from the keyboard and validate it as integer within the range (0-9)
// Assign user input value into cNumber variable
char cNumber;
cin >> cNumber;
// Subtract ASCII value of zero from cNumber and assign value to iNumber variable
int iNumber = cNumber - 48;
if (iNumber < 0 || iNumber > 9)
{
cerr << cNumber << " is not within the range of (0-9)" << endl;
}
else
{
cout << "The result is " + iNumber * 2;
}
}
}
相关文章:
- C 控制台程序中的内存泄漏调用Windows API
- 您如何编译C 控制台程序以作为Android流程运行
- Q无法执行简单的控制台程序
- 无法使用 QProcess 运行简单的控制台程序
- 如何防止我的屏幕截图制作控制台程序阻止屏幕截图
- 如何从C ++控制台程序连接到MS SQL SERVER
- 控制台程序读取文本文件行,做Levenstein并输出一个文本文件
- 为什么控制台C++程序在Visual Studio中具有不同的起始代码
- C++控制台程序的前端
- C++控制台程序崩溃,没有任何错误
- 我在一个简单控制台程序(c++)中的第一列代码最终成为我的最后一列
- 单击“关闭控制台窗口”结束 C++ 控制台程序是正确的方法
- 如何将字符串从缓冲区粘贴到控制台程序
- 执行控制台程序,写入标准输入并使用管道读取结果
- C++控制台程序在完成之前关闭
- 如何使我的控制台C++程序在后台运行
- c++控制台程序中strcpy函数的异常.strcpy()中的
- 如何进入控制台程序并从中读取
- 从任务栏隐藏控制台c++程序
- 按键即可打开/关闭控制台程序