473,698 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Making a string into a c++ line of code

I'm working on a simple calculator similar to the MS Calculator in
visual c++ 6.0. I'm trying to teach myself the visual aspect of c++ on
my own time, so I've decided to jump right into a program after reading
through a lot of material that has gotten me familiar with it.

I have a result edit box at the top of the window which holds whatever
is being typed in via the numerical buttons and arithmetic buttons (+,
-, *, /). Each numerical digit will add its number (a string) to the
result edit box (making the result's string larger). Eventually, the
edit box may contain-> 6+3+2-4*8, all in a string.
When I press the enter button on my calculator, I would like the
program to just convert the edit box's content (the string) to the
result; in this case the box would contain -21 (following the default
order of operations).

I've looked around on the internet for some time as well as my several
c++ books - I have been unable to find anything remotely related to
what I want to do, and am starting to assume it can not be done since I
see no way a compiled program will interact with a line of code. Can
someone please help me? Thanks for your time.

Mar 4 '06 #1
5 2471
TB
bs********@isp. com skrev:
I'm working on a simple calculator similar to the MS Calculator in
visual c++ 6.0. I'm trying to teach myself the visual aspect of c++ on
my own time, so I've decided to jump right into a program after reading
through a lot of material that has gotten me familiar with it.

I have a result edit box at the top of the window which holds whatever
is being typed in via the numerical buttons and arithmetic buttons (+,
-, *, /). Each numerical digit will add its number (a string) to the
result edit box (making the result's string larger). Eventually, the
edit box may contain-> 6+3+2-4*8, all in a string.
When I press the enter button on my calculator, I would like the
program to just convert the edit box's content (the string) to the
result; in this case the box would contain -21 (following the default
order of operations).

I've looked around on the internet for some time as well as my several
c++ books - I have been unable to find anything remotely related to
what I want to do, and am starting to assume it can not be done since I
see no way a compiled program will interact with a line of code. Can
The string is not code. It's input and it's up to you to parse it.
someone please help me? Thanks for your time.


It's rather simple. This is a perfect project to get a feeling for
implementing algorithms.

(See for example Operator-precedence parsing.) There is a lot of
information about this on the Internet, e.q.:

http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
http://www.cs.princeton.edu/introcs/44stack/
http://www.willamette.edu/~fruehr/348/lab3.html

--
TB @ SWEDEN
Mar 4 '06 #2
* bs********@isp. com:
I'm working on a simple calculator similar to the MS Calculator in
visual c++ 6.0. I'm trying to teach myself the visual aspect of c++ on
my own time, so I've decided to jump right into a program after reading
through a lot of material that has gotten me familiar with it.

I have a result edit box at the top of the window which holds whatever
is being typed in via the numerical buttons and arithmetic buttons (+,
-, *, /). Each numerical digit will add its number (a string) to the
result edit box (making the result's string larger). Eventually, the
edit box may contain-> 6+3+2-4*8, all in a string.
When I press the enter button on my calculator, I would like the
program to just convert the edit box's content (the string) to the
result; in this case the box would contain -21 (following the default
order of operations).

I've looked around on the internet for some time as well as my several
c++ books - I have been unable to find anything remotely related to
what I want to do, and am starting to assume it can not be done since I
see no way a compiled program will interact with a line of code. Can
someone please help me? Thanks for your time.


This is probably a FAQ -- check the FAQ.

Anyway, you can code an expression evaluator yourself, or find and use
an existing one.

Here's a very simple one, that only works for very simple expressions
and only in Microsoft Windows (which is the OS you're using):

#include <cstdlib> // std::system
#include <iostream> // std::cin, std::cout
#include <istream> // operator>>
#include <fstream> // std::ifstream
#include <ostream> // operator<<, std::endl
#include <stdexcept> // std::runtime_er ror
#include <string> // std::string, std::getline

double eval( std::string const& s )
{
char const filename[] = "calcresult.txt ";

// Microsoft Windows.
std::system( ("set /a " + s + " >" + filename).c_str () );
std::ifstream resultFile( filename );
double result;
resultFile >> result;
if( resultFile.fail () ) { throw std::runtime_er ror( "Oops" ); }
return result;
}

int main()
{
std::string expression;

std::cout << "Enter a numeric expression: ";
std::getline( std::cin, expression );
try
{
std::cout << eval( expression ) << std::endl;
return EXIT_SUCCESS;
}
catch( std::exception const& x )
{
std::cerr << "!" << x.what() << std::endl;
return EXIT_FAILURE;
}
}


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Mar 4 '06 #3
Alf P. Steinbach wrote:
Anyway, you can code an expression evaluator yourself, or find and use an
existing one.


This one doesn't suck (in my exalted opinion):

http://www.xpsd.org/cgi-bin/wiki?Rec...scentParserCpp

Note how my techniques make adding new features to the parser very, very
easy.

Warning: Inventing new languages on the fly is a bad habit. If this were my
project, I would link to Ruby, and evaluate arbitrarily complex expressions
with only a few lines of C++.

--
Phlip
http://www.greencheese.org/ZeekLand <-- NOT a blog!!!
Mar 4 '06 #4
TB - thanks for letting me know what it was that I was trying to do.
I've read into a lot about parsing now, and now know what it is and how
the several methods are accomplished.
Alf - I used your parser, and it works well for simple things. I've
tried to implement a decimal feature into it, but to no avail.
Phlip - I tried your parser - it works very well as far as I can tell,
but I can not figure out how to input a string value into your parser
(a lot of your syntax looks foreign....I'm trying to figure out what
much of it does). I also looked into Ruby, but I think I'm going to
stick to C++ for parsing for now, even though it will be much more
challenging and time-consuming.

I also have found another expression parser (very well detailed, and
also easily understandable, though older code) at
http://www.dcs.qmul.ac.uk/~keithc/co...96-04-026.html,
but as in Alf's parser, I've been unable to implement decimal numbers
into it (I'm using 1+1.01 as a test expression, but can not get it to
work and output the answer of 2.01). Any more ideas will be greatly
appreciated - thanks for all of your help.

Mar 9 '06 #5
bs********@isp. com wrote:
TB - thanks for letting me know what it was that I was trying to do.
I've read into a lot about parsing now, and now know what it is and how
the several methods are accomplished.
Alf - I used your parser, and it works well for simple things. I've
tried to implement a decimal feature into it, but to no avail.
Phlip - I tried your parser - it works very well as far as I can tell,
but I can not figure out how to input a string value into your parser
(a lot of your syntax looks foreign....I'm trying to figure out what
much of it does). I also looked into Ruby, but I think I'm going to
stick to C++ for parsing for now, even though it will be much more
challenging and time-consuming.

I also have found another expression parser (very well detailed, and
also easily understandable, though older code) at
http://www.dcs.qmul.ac.uk/~keithc/co...96-04-026.html,
but as in Alf's parser, I've been unable to implement decimal numbers
into it (I'm using 1+1.01 as a test expression, but can not get it to
work and output the answer of 2.01). Any more ideas will be greatly
appreciated - thanks for all of your help.


The OP has fallen out of my buffer so forgive me if I'm off-topic here
but speaking of parsers, I have just used the boost spirit parser for a
project and found it to be excellent. I highly recommend it.

-York
Mar 9 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4172
by: Kenneth McDonald | last post by:
I'm working on the 0.8 release of my 'rex' module, and would appreciate feedback, suggestions, and criticism as I work towards finalizing the API and feature sets. rex is a module intended to make regular expressions easier to create and use (and in my experience as a regular expression user, it makes them MUCH easier to create and use.) I'm still working on formal documentation, and in any case, such documentation isn't necessarily the...
1
6221
by: Rune Runnestø | last post by:
Hi, I have made a small program that doesn't work quite the way it should. It is a guestbook for the web, where visitors can write back their greetings. The program consists of 3 files: - guestbook.jsp -> this is the form - writeToFile -> writing the captured data from the form to a file - readFromFile -> reading all the greetings to the file guestbook.jsp Here is the file Guestbook.jsp: ------------------------------ <!--...
3
10280
by: sklett | last post by:
This BUG that is so ridiculous I can't believe they shipped 05 is making my life hell. I have tried the various solutions found on the web and none of them have worked thus far. What's even more troublesome is that it appears that 05 uses these new partial classes which would makes rolling back to 03 not possible. The error I get when trying to load my Form in the designer is as follows:...
351
12987
by: CBFalconer | last post by:
We often find hidden, and totally unnecessary, assumptions being made in code. The following leans heavily on one particular example, which happens to be in C. However similar things can (and do) occur in any language. These assumptions are generally made because of familiarity with the language. As a non-code example, consider the idea that the faulty code is written by blackguards bent on foulling the language. The term...
18
1735
by: dbahooker | last post by:
team i'm having a tough time getting these data readers to work correctly I'd just like to be able to centralize my GetDataReader functions; so i can pass a simple SQL statement and be passed back a valid DataReader object. I've been slaving with this all day long. I've been trying 'new' and not new and just slaving over this; im calling it an early day..
7
20563
by: John Salmon | last post by:
I'm working with two libraries, one written in old school C, that returns a very large chunk of data in the form of a C-style, NUL-terminated string. The other written in a more modern C++ is a parser for the chunk of bytes returned by the first. It expects a reference to a std::istream as its argument.
5
1895
by: Andy B | last post by:
I am trying to figure out how to make an object instance available for all methods of a class. I tried to do something like this: public class test { TheObject Instance = new TheObject(); TheObject.Dictionary<string, string= new Dictionary<string, string>(); .... } The first line (TheObject instance = new TheObject();) doesn't get
11
6248
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute instead of the wrapped version. Does anyone have a simple solution for this?
8
4039
by: sheldoncs | last post by:
System.InvalidOperationException was unhandled Message="Client found response content type of 'text/plain; charset=utf-8', but expected 'text/xml'. The request failed with the error message: -- System.Web.Services.Protocols.SoapException: Server was unable to process request. ---> System.UnauthorizedAccessException: Access to the path 'd:\logFile.txt' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at...
0
8680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8899
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7738
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4371
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2335
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.