C++: How do I accept a whole formula?

Uconn411

Member
Jul 15, 2000
152
0
0
I would like a program to accept a formula based on y=ax+b, such as Y=1.36X+3.6. How do I read this formula using cin? I don't want couts that ask the user to input values for a and b. I just want the whole formula to be read, correctly. Thanks for any help....
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
Assignment for class?
If you just want to accept "y = ax + b" and not any formula, it's pretty simple.
1. read the whole line into a string
2. split the string into sub-strings for the proper parts (can throw away all except a and b)
3. use atof() on the a, b parts.

2. is of course the hard part, you must know how to traverse a string character-by-character and how to create a string from part of another string.

Hopefully no one will post a working program, so you can learn on your own.


 

Uconn411

Member
Jul 15, 2000
152
0
0
Thanks for the reply. I honestly do want to learn on my own. I was trying to split it into parts as int, using cin. I will now try to read it as a string. Thanks.
 

Arrgghh

Member
Nov 25, 2001
33
0
0
Nothing wrong with DaveSimmon's answer, but if you'd like to do it in a more c++ oriented way you may consider string streams
#include <sstream>
.
.
istringstream iss(temp); //temp a string holding the substring you want
iss >> a; //where a is any other type

 

manly

Lifer
Jan 25, 2000
13,016
3,775
136
If the formula is in a well-defined format (such as y = ax + b), I believe you can use scanf as the simplest API for what you want to do.

Then again I'm a Java hacker, so don't quote me on the solution. ;) In Java, probably the most convenient way is to use a regex package like Jakarta ORO and feed in the line of input to a pattern matcher. But I digress...
 

m0ti

Senior member
Jul 6, 2001
975
0
0
PYTHON!!

nah, just kiddin'

scanf is the easiest way to go, though it defines an exact format (no extra spacing for you!)
 

Sestar

Senior member
Dec 26, 2001
316
0
0
where c is a charachter d is a double, and x is an int
cin>>c>>c;//takes care of the y and the =
cin>>d>>c>>c>>x;//takes care of the rest, I dunno, usually works for me