1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
|
/*
* parser.cpp
*
* Created on: Oct 2, 2012
* Author: michaela
*/
#include <iostream>
#include <fstream>
#include <string>
std::string s;
char token;
int error;
void exp(std::ofstream& outf, std::ifstream& inf);
void gettoken(std::ofstream& outf, std::ifstream& inf)
{
static int pos = 0;
token = s[pos];
outf << "\n<gettoken> " << token << " ";
if(token == '$')
pos = 0;
else
++pos;
}
void digit(std::ofstream& outf, std::ifstream& inf)
{
if(token != '$')
outf << "<digit>";
if(token >= '0' && token <= '9')
gettoken(outf, inf);
else
error = 1;
}
void number(std::ofstream& outf, std::ifstream& inf)
{
if(token != '$')
outf << "<number>";
digit(outf, inf);
}
void factor(std::ofstream& outf, std::ifstream& inf)
{
if(token != '$')
outf << "<factor>";
if(token == '(')
{
gettoken(outf, inf);
exp(outf, inf);
if(token == ')')
gettoken(outf, inf);
else
error = 2;
}
else
number(outf, inf);
}
void term(std::ofstream& outf, std::ifstream& inf)
{
outf << "<term>";
factor(outf, inf);
while(token == '*'){
gettoken(outf, inf);
factor(outf, inf);
}
}
void exp(std::ofstream& outf, std::ifstream& inf)
{
outf << "<exp>";
term(outf, inf);
while(token == '+') {
gettoken(outf, inf);
term(outf, inf);
}
}
int main()
{
std::ifstream inf("in.dat");
std::ofstream outf("out.dat");
error = 0;
while (!inf.eof())
{
getline(inf, s);
std::cout << s << std::endl;
gettoken(outf, inf);
exp(outf, inf);
if(error == 0)
outf << "\nThe parse has been completed with no problems!!!\n\n";
else
{
outf << "\nThe parse failed...\n";
switch(error)
{
case 1:
outf << "A digit did not follow an operator...\n";
break;
case 2:
outf << "There was no closing parenthesis...\n";
break;
}
}
}
inf.close();
outf.close();
return 0;
}
|