【发布时间】:2016-02-16 03:46:22
【问题描述】:
我需要制作一个运行单行输入并从左到右读取它的 c++ 程序。在输入结束时,用户添加 # 表示输入完成。我让计算器工作,但是如果用户只输入 # 并点击进入程序需要能够抛出错误代码。否则我们可以假设用户输入正确。这是我到目前为止的代码。
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int var1, var2, total;
char operation;
cout << "Enter an equation: ";
cin >> var1;
/*if (var1 == 0)
{
cout << "error";// cant pass in info via char because var1 is
return 1; // in the way and using var == 0 technique is
* // cheating because then you can't do 0#
*/
else
{
do
{
cin >> operation;
if (operation == '#')
{
cout << var1;
}
else
{
cin >> var2;
}
if(operation == '+')
total = var1 + var2;
else if(operation == '-')
total = var1 - var2;
else if(operation == '/')
total = var1 / var2;
else if(operation == '*')
total = var1 * var2;
var1 = total;
}while (operation != '#');
}
return 0;
}
问题是我知道我需要先运行 cin var 1 才能执行任何其他操作。无论如何,我是否可以在不更改输入的情况下获取输入的第一个字符?我真的不知道还能做什么。如果有什么需要澄清的,请询问。
【问题讨论】:
标签: c++ calculator