我有一個簡單的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)它會顯示第一個字符,但表達式不會使用字符。