Sign in to follow this  

[Clarification Needed] Is this even a parser ?

This topic is 3290 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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[i]=='+' || x[i]=='-' || x[i]=='*' || x[i]=='/') //When one of these signs is encountered
		{
			op = x[i];
			bookmark = i;}
	}

	for(int i = 0; i<bookmark; i++)
		val1 = val1 * 10 + (x[i]-'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[i]-'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 ;)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 3290 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this