I am reading strings from a file and evaluating them. example file:
9+9
9+5-1
8.5
25.5-1.9-32
89.1+9-2
It works great until it gets to a float where the operator is a '-' but when Its a '+' it works normal.
So for 89.1+9-2 it works but for 25.5-1.9-32 it crashes and I've tried print out my tokens to see how its working.
Whenever its doing the 25.5-1.9-32, instead of first completing the token 25.5 (like it does for the rest) then evaluating it, it's stopping after each char which is weird and I'm not sure what is causing it.
when doing the 89.1+9+2, my tokens complete then evaluate, eg. 89.1, then my token is 9 then its 2 which is what i want.
when its doing the 25.5-1.9-32, my tokens for some reason don't complete and instead is 2, then 5, then ., then 1, then 1, then . then 9 etc.
Please have a look below and let me know why when doing subtraction my tokens stop at each char instead of completing the token first.
// Example program #include <iostream> #include <string> int main() { string x = "89.1+9-2" (change to "25.5-1.9-32", to see my problem). float val = 0; string t = ""; string op = ""; //note x is just my string, so it will go through the string until its finished then go to the next line/string. for (int i = 0; i < x.size(); i++) { char c = x[i]; switch (c) { case '+': op = "+"; break; case '-': op = "-"; break; default: t += c; break; } if (t != "") { if (op == "+") { //cout << "t " << t << endl; val += stof(t); //cout << "v " << val << endl; t = ""; //clear t once we're done with it } if (op == "-") { cout << "t- " << t << endl; if (val != 0) { val -= stof(t); } else { val += stof(t); t = ""; } cout << "v- " << val << endl; } } } if (val != 0) { cout << "Expression " << x << " gives " << val << endl; } else { cout << "Expression " << x << " gives " << x << endl; } } return 0; }
https://stackoverflow.com/questions/67342010/c-parsing-error-when-dealing-with-floats May 01, 2021 at 08:56AM
没有评论:
发表评论