Question

I have a lot of symbolic expressions with the power symbol which I want to copy in a C++ program. However they have the power symbol ^ which is not used in C. Any advice for making the change fast? Should I use regular expressions of i can make gcc to see ^ as pow()?

Was it helpful?

Solution

To be certain not to foul anything up, you'd need a parser that knows when a ^ is actually being used as a power symbol (and not for example in a comment, a string).

But you might get away with a simple regex:

Replace (\w+)\s*\^\s*(\w+) with pow(\1,\2).

That should cover most cases and be reasonably safe.

Of course, it will fail if there are more parameters, like in (a + b) ^ (c + d) etc. This regex only matches things like a^b or 2^3. It also doesn't match x^0.5 correctly, so if those may occur, you'd need ([\w.]+)\s*\^\s*([\w.]+)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top