Vs2012 calculator 程序输出异常。
#include <iostream>
#include <iomanip>
//#include <stdlib.h>
//#include <cstdarg>
#include <cctype>
using std::cout;
using std::cin;
using std::endl;
using std::setw;
using std::cerr;
const size_t MAX= (80);
void eatspaces(char* str);
double expr(const char* str);
double term(const char* str,size_t& index);
double number(const char*str,size_t& index);
//8.2*9+2.6/1.5+12-3.7*2.9+5.6*4.2-5.0/1.4+7.00-9.1-100
void eatspaces(char* str);
int main()
{
char buffer[MAX]= {0}; // Input area for expression to be evaluated
cout << endl
<< "Welcome to your friendly calculator."
<< endl
<< "Enter an expression, or an empty line to quit."
<< endl;
for (;;)
{
cin.getline(buffer, sizeof buffer); // Read an input line
eatspaces(buffer); // Remove blanks from input
if (!buffer[0]) // Empty line ends calculator
return 0;
try
{
cout << "\t= " << expr(buffer) // Output value of expression
<< endl << endl;
}
catch (const char* pEx)
{
cerr << pEx << endl;
cerr << "Ending program." << endl;
return 1;
}
}
}
//Funtion to eliminate spaces from a string
void eatspaces(char* str)
{
size_t i=0; //"copy to " index to string
size_t j=0; //"copy from " index to string
while((*(str+i)=*(str+j++)) !='\0')
if(*(str +i)!=' ')
i++;
return;
}
//Function to evaluate an arithmetic expression
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 evaluation error. Found: ";
strncat_s(message,str+index-1,1); //Append the character
throw message;
break;
}
}
}
}
//Function to get the value of a term
double term (const char* str,size_t& index)
{
double value=0;
value =number(str,index);
//Loop as long as we have a good operator
while(true)
{
if(*(str+index)=='*')
value *=number(str,++index);
else if(*(str+index)=='/')
value /=number(str,++index);
else break;
}
return value;
}
//function to recognize a number in a string
double number(const char* str,size_t& index)
{
double value=0;
//There must be at least one digit...
if (!isdigit(*(str+index)))
{ //There's no digits so input is junk...
char message[35]="Invalide character in number : ";
strncat_s(message,str+index,1); //Append the character
throw message;
}
while(isdigit(*(str+index)))
value=10*value+(*(str +index++)-'0');
if(*(str+index)!='.')
return value;
double factor=1.0;
while(isdigit(*(str+(++index))))
{
factor*=0.1;
value=value*(*(str+index)-'0')*factor;
}
return value;
}
原因分析:
while(isdigit(*(str+(++index))))
{
factor*=0.1;
value=value*(*(str+index)-'0')*factor;
}
其中第四行代码打错,误将”+“打在了“*”。导致异常出现,更正后程序调试正常。
更正为:
value=value+(*(str+index)-'0')*factor;
补充知识: