[Clarification Needed] Is this even a parser ?

Started by
1 comment, last by ToohrVyk 15 years, 4 months ago
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;

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;
	}

}

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 ;)
Advertisement
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.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

You could take a peek at this.

Your program contains a lexer, a parser and the semantic actions for the parser, all in one location. It does not handle precedence and it backtracks (though arguably not a problem).

This topic is closed to new replies.

Advertisement