Click here to Skip to main content
15,891,787 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I am inputing a string like 12+13 = a ;
IT can be like this also : 12+ a = 25 ; or the other way around ,

now I want that what my output is 12 + 13 = 25;

Now the ques is that I am inputing it using getline(cin,str); now I don't know the characters in that which I can use to get the answer

what is your opinion to solve this .
Posted
Comments
Prerak Patel 27-Jul-11 1:34am    
Are you trying to make expression solver?
ThatsAlok 27-Jul-11 5:47am    
you can use regular expression!

I guess you can use strtok function.
Link for the function http://www.cplusplus.com/reference/clibrary/cstring/strtok/[^]
 
Share this answer
 
Split the string into tokens as explained in Solution 1.

Initialize an integer accumulator as 0, and a sign flag as positive.

Scan the list to identify the tokens (ignore the last one):

- every even token is either a number or a variable name,

- every odd token is either a + or an = .

To tell a number from a variable name, use sscanf("%d", ...) and check that it decodes one value. If number, accumulate it with its sign; if variable, save the sign.

When you meet the = token, change the sign flag to negative.

As you go analysing the string, construct another string by copying all tokens verbatim, except for the variable name, which you replace by "%d". (Alternatively, replace the variable name by %d in the original string.)

Format the result string by means of printf, passing the contructed string and the accumulator value taken with the sign of the variable, negated.

There you are. About a dozen lines of code. Totally unsafe to misformed input strings.
 
Share this answer
 
v2
Comments
YvesDaoust 27-Jul-11 6:40am    
CAUTION: strtok won't work here when there are no space separators
For one, this is not a 'simple string' problem, you want a Lexical Analyzer. There are libraries that solve the problem of tokenizing a text and structuring it in a sensible way, given set of grammatical rules. See the various references provided on the site linked above.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900