【发布时间】:2016-10-18 12:29:39
【问题描述】:
我有一个简单的 c++ 计算器,我试图让程序在空输入时退出(输入键)。我可以让程序退出并继续;但是程序会忽略第一个字符。
#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <conio.h>
using namespace std;
float a, b, result;
char oper;
int c;
void add(float a, float b);
void subt(float a, float b);
void mult(float a, float b);
void div(float a, float b);
void mod(float a, float b);
int main()
{
// Get numbers and mathematical operator from user input
cout << "Enter mathematical expression: ";
int c = getchar(); // get first input
if (c == '\n') // if post inputs are enter
exit(1); // exit
else {
cin >> a >> oper >> b;
// operations are in single quotes.
switch (oper)
{
case '+':
add(a, b);
break;
case '-':
subt(a, b);
break;
case '*':
mult(a, b);
break;
case '/':
div(a, b);
break;
case '%':
mod(a, b);
break;
default:
cout << "Not a valid operation. Please try again. \n";
return -1;
}
//Output of the numbers and operation
cout << a << oper << b << " = " << result << "\n";
cout << "Bye! \n";
return 0;
}
}
//functions
void add(float a, float b)
{
result = a + b;
}
void subt(float a, float b)
{
result = a - b;
}
void mult(float a, float b)
{
result = a * b;
}
void div(float a, float b)
{
result = a / b;
}
void mod(float a, float b)
{
result = int(a) % int(b);
}
我尝试使用 putchar(c) 它将显示第一个字符,但表达式不会使用该字符。
【问题讨论】:
标签: c++