我在运行下面的代码时遇到问题
我所需要做的就是让用户输入一个整数,然后将其保存到我的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;
}
}
}