参考自《Visula C++2013入门经典第七版》
从命令行输入表达式,然后分解识别各个符号间的数值,并进行相加减乘除,可支持小数点
// command_line_calculator.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <cstdlib> //for exit()
#include <cctype> //for isdigit() 对单字符的操作
using namespace std;
void eatspaces(char* str);
double expr(const char* str);
double term(const char* str, size_t& index);
double numble(const char* str, size_t& index);
const size_t MAX{ 80 };
int main()
{
char buffer[MAX] = {};
cout << endl
<< "Welcome to your friendly calculation."
<< endl
<< "Enter an expression , or an empty line to quit"
<< endl;
for (;;)
{
cin.getline(buffer, sizeof buffer);
eatspaces(buffer);
if (!buffer[0])
return 0;
try
{
cout << "\t=" << expr(buffer) << endl << endl;
}
catch (const char* str)
{
cerr << str << endl;
cerr << "Ending program. " << endl;
return 1;
}
}
system("pause");
return 0;
}
//数组内复制移位,如果str【i】是空格,i就不会+1,只有j逐步+1
void eatspaces(char* str)
{
size_t i = 0;
size_t j = 0;
while ((*(str + i) = *(str + j++))!= '\0')
if (*(str + i) != ' ')
i++;
return;
}
//分析数
double number(const char* str, size_t& index)
{
double value = 0;
if (!isdigit(*(str + index)))
{
char message[31]= "INVALID character in number: ";
strncat_s(message, str + index, 1);
throw message;
}
while (isdigit(*(str + index)))
value = 10 * value + (*(str + index++) - '0');
if (*(str + index) != '.')
return value;
//以下为读取小数点后面的值 ,上面当数字后面的符号不是.就代表计算结束,返回value
double factor = 1.0;
while (isdigit(*(str + (++index)))) //因为。的原因,所以是 ++ index,判断出小数点区段的数字内容。
{
factor *= 0.1;
value = value + (*(str + index) - '0')*factor; //字符串中数字为ASCII码,转换成十进制需要减去‘\0’ (48)
}
return value;
}
double term(const char* str, size_t& index)
{
double value = 0;
value = number(str, index);
while (true)
{
if (*(str + index) == '*')
value *= number(str, ++index);
else if (*(str+index) == '/')
value /= number(str, ++index);
else
break;
}
return value;
}
//计算表达式值
double expr(const char *str)
{
double value = 0;
size_t index = 0;
value = term(str, index);
for (;;)
{
switch (*(str + index++))
{
case '\0':
return value;
case '+':
value += term(str, index);
break;
case '-':
value -= term(str, index);
break;
default:
char message[38] = "Expression evalation error. Found: ";
strncat_s(message, str + index - 1, 1);
throw message;
break;
}
}
}