Emily Evelan Emily Evelan - 3 years ago 152
C++ Question

Split a 3-variable equation into doubles and characters in C++

I'm working on an assignment with equations, but I can't figure out how to input the different parts of the equation.

The equation is always formatted:

An example: 2.5y+4.7x+7z=46

To accomplish this, I tried using four double variables and six character variables.

double a,d,g,j;

char b,c,e,f,h,i;

so that the equation splits into the variables a b c d e f g h i, which I can then manipulate.

If there were whitespaces anywhere in the equation, I could have used istringstream to split them, but there aren't. I am not allowed to change the input file.

How can I put the numbers in doubles, and the letters/symbols in characters?

Answer Source

You can use istringstream and out of stream operator. For example:

std::istringstream iss("2.5y+4.7x+7z=46");
double a,b,c,s;
char v1,v2,v3;
iss >> a; // read 1st koef
iss >> v1; // read 1st var's name 
iss >> b; // read 2nd koef
iss >> v2; // read 2nd var's name
iss >> c; // read 3rd koef
iss >> v3; // read 3rd var's name
iss.ignore(); // skip '=' symbol
iss >> s; // read sum

Signs in equation is sign of relevant koefs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download