【发布时间】:2018-06-16 13:58:33
【问题描述】:
我最近在尝试一些计算器的代码,我找到了一个可以工作的..
但是无论我尝试什么,这个程序都会在控制台上显示答案后立即关闭。请帮助我,我尽力让它停止。但它不会工作......
我使用Visual Studio进行编码,如果与它相关,请通知我
#include <iostream>
#include <string>
#include <cctype>
#include<conio.h>
int expression();
char token() {
char ch;
std::cin >> ch;
return ch;
}
int factor() {
int val = 0;
char ch = token();
if (ch == '(') {
val = expression();
ch = token();
if (ch != ')') {
std::string error = std::string("Expected ')', got: ") + ch;
throw std::runtime_error(error.c_str());
}
}
else if (isdigit(ch)) {
std::cin.unget();
std::cin >> val;
}
else throw std::runtime_error("Unexpected character");
return val;
}
int term() {
int ch;
int val = factor();
ch = token();
if (ch == '*' || ch == '/') {
int b = term();
if (ch == '*')
val *= b;
else
val /= b;
}
else std::cin.unget();
return val;
}
int expression() {
int val = term();
char ch = token();
if (ch == '-' || ch == '+') {
int b = expression();
if (ch == '+')
val += b;
else
val -= b;
}
else std::cin.unget();
return val;
}
int main(int argc, char **argv) {
try {
std::cout << expression();
}
catch (std::exception &e) {
std::cout << e.what();
}
return 0;
}
【问题讨论】:
标签: c++ windows visual-studio