void stringParse(string x)
{
int val1 = 0, val2 = 0;
int bookmark; //Will store the position of the sign to be used ( be it + , * , / , - )
char op; //Stores the char value of that for later use in the switch part
int size = x.size();
for(int i = 0; i<size; i++)
{
if(x=='+' || x=='-' || x=='*' || x=='/') //When one of these signs is encountered
{
op = x;
bookmark = i;}
}
for(int i = 0; i<bookmark; i++)
val1 = val1 * 10 + (x-'0'); //Transforms the array of elements to the left of the bookmark to a single integer
for(int i = bookmark+1; i<size; i++)
val2 = val2 * 10 + (x-'0'); //Transforms the array of elements to the left of the bookmark to a single integer
//Pretty straightforward:
switch(op){
case '-':
cout<<val1-val2<<endl;break;
case '+':
cout<<val1+val2<<endl;break;
case '*':
cout<<val1*val2<<endl;break;
case '/':
cout<<val1/val2<<endl;break;
}
}
[Clarification Needed] Is this even a parser ?
Hello,
Well, from what I read, a parser is converting a string inputted by the user to a 'recognizable one', one which can be processed. So, giving it a go, I went ahead a made a calculator;
Could this even be considered a BASIC string parser ? ( I am aware it has a lot of problems, but... BASIC ) or am I just going a totally different path ?
In either case, help / useful links are greatly apreciated ;)
If it accepts textual input and produces output, it is a parser [smile]
In all seriousness, simple calculators are the bread and butter of most of the tutorials and books on learning to write parsers. They are a decent way to introduce some fairly advanced concepts (operator precedence and grouping, function calls, variables), while remaining simple enough to implement quickly and have a demonstrable result.
I am afraid I don't have any links for you, since I learned to program parsers by reading the boost::spirit and bison manuals, and later brushed it over with a basic compilers course in college - not the generally recommended method, I can assure you, though it served me well enough.
In all seriousness, simple calculators are the bread and butter of most of the tutorials and books on learning to write parsers. They are a decent way to introduce some fairly advanced concepts (operator precedence and grouping, function calls, variables), while remaining simple enough to implement quickly and have a demonstrable result.
I am afraid I don't have any links for you, since I learned to program parsers by reading the boost::spirit and bison manuals, and later brushed it over with a basic compilers course in college - not the generally recommended method, I can assure you, though it served me well enough.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement