我正在学习使用 C++ 的原理和实践
。我已经很好地理解了它,但最近我在第 6 章
上遇到了困难。假设您开始编写一个计算器程序,随着您的继续,它的功能逐渐变得更加丰富。它最终会导致代币的出现,这让我很困惑。
任何人!我的问题是,我正在遵循这段代码,但它没有按照它所解释的那样工作。我已经对照这本书检查了几次代码,看起来很相似。代码只是不断地接收 lval 而不用它做任何事情。 3 cin 条目后,它只会显示 lval 最初设置的值。我也不是 100% 确定在 while 循环中使用 cin >> op 。是什么让它停止?它什么时候知道停止?错误函数似乎也不起作用。我一直试图破坏该程序,但它没有弹出任何错误消息。
这真是令人沮丧,因为我正在学习,如果没有导师,我很难解决自己的问题:/不过感谢大家的宝贵时间!传入代码...这是我到目前为止所拥有的
#include "std_lib_facilities.h"
int main()
{
cout << "Please enter an expression (we can handle ""+"",""-"",""*"",""/"")" << endl;
int lval = 0;
int rval;
char op;
/*int res;*/
cin >> lval; //read left most number
if (!cin) error("No first operand");
while (cin >> op) //Repeatedly read operand and right value
{
cin >> rval;
if (!cin) error("No second operand");
switch(op)
{
case '+':
lval += rval; //add: lval = lval + rval
break;
case '-':
lval -=rval;//subtract: lval = lval - rval
break;
case '*':
lval *= rval; //Multiply: lval = lval * rval
break;
case '/':
lval /= rval; //Divide: lval = lval / rval
break;
default:
cout << "Result: " << lval << endl;
keep_window_open();
return 0;
}
}
error("Bad expression");
}
附注我尝试使用断点来查看如何逐行编码,但它开始让我陷入 iostream 文件中,而我此时不知道如何阅读这些文件!
最佳答案
它确实起作用了。例如,如果您引入以下序列:
3 <enter>
+ <enter>
3 <enter>
d <enter>
3 <enter>
它产生:
Result: 6
原因是 cin 总是期望输入结束。逻辑上也有错误,即使你想停止执行,你也必须引入一个额外的虚拟值。要解决这个问题,您必须在请求 rval 之前检查运算符。
编辑:
可能这会接近你想要的:
#include "iostream"
#include <cstdio>
using namespace std;
int main()
{
cout << "Please enter an expression (we can handle ""+"",""-"",""*"",""/ "")" << endl;
int lval = 0;
int rval;
char op;
/*int res;*/
cin >> lval; //read left most number
if (!cin) printf("No first operand");
while (cin >> op) //Repeatedly read operand and right value
{
if(op != '+' && op != '-' && op != '*' && op != '/')
{
cout << "Result: " << lval << endl;
//keep_window_open();
getchar();
return 0;
}
cin >> rval;
if (!cin) printf("No second operand");
switch(op)
{
case '+':
lval += rval; //add: lval = lval + rval
break;
case '-':
lval -=rval;//subtract: lval = lval - rval
break;
case '*':
lval *= rval; //Multiply: lval = lval * rval
break;
case '/':
lval /= rval; //Divide: lval = lval / rval
break;
}
}
printf("Bad expression");
}
关于c++ - "Principles and Practice Using C++"第6.3.1章代码错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924710/