• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

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

Uconn411

Member
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....
 
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.


 
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.
 
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

 
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...
 
PYTHON!!

nah, just kiddin'

scanf is the easiest way to go, though it defines an exact format (no extra spacing for you!)
 
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
 
Back
Top