0

So, I need to make a script that can receive an equation stored in a string, and then solve said equation. I want to use popen() to call in the bc program to solve said equation, but I'm not sure exactly how to do that. All the resources I've seen take their input from a FILE or stdin, and none of them explain how to call bc, then give it a string input. I'm not very good at coding in C yet, so I have a very hard time coming up with a solution to this.

I don't know exactly what the equations will be, but they won't be more complex than integers and a few basic operations.

  • One of the most important programming skills is breaking complex problems down into simple ones. You should try this yourself, both because it'll help you learn this technique and also because no attempt is [off-topic for SO](https://stackoverflow.com/help/on-topic). See [ask]. In fact, you've done a good job of breaking down the problem already. Step 1: figure out how to collect an equation in an input string. Step 2: figure out how to run a subprocess and get the result (doesn't have to be `bc`--you can adapt what you find to run the proc you want). Good luck! – ggorlen Apr 13 '20 at 01:31
  • It's my fault for not being clearer. I need to use bc in my code, but I cannot find a resource that tells me how, except for in a bash script. Which is not what I'm doing. Since the equation I am being given is in a format that bc can interpret, and random in such a way that trying to write my own code to solve the equation is impossible. My only clue is to use popeon to call bc, and then give it the equation as a string. So I am asking for someone to tell me: (A. How to call bc into a script (B. How to feed it an equation from a string Because I cannot find this information ANYWHERE – Duncan Cross Apr 13 '20 at 19:59
  • I think you may be a bit too fixated on `bc`. Basically, if you can learn to how run any bash command in C, give it arguments and get its output as a string, all you have to do is substitute `bc`, along with sensible arguments, in place of whatever the examples show. Here are a few threads: [1](https://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output), [2](https://stackoverflow.com/questions/5237482/how-do-i-execute-external-program-within-c-code-in-linux-with-arguments), [3](https://stackoverflow.com/questions/3736210/how-to-execute-a-shell-script-from-c-in-linux) – ggorlen Apr 13 '20 at 20:25
  • In fact, I was able to get it working using [the top answer in this thread](https://stackoverflow.com/a/646254/6243352) and changing the `ls` command they used to `fp = popen("echo \"12+5\" | bc", "r");`. You'll still need to figure out how to [interpolate the expression into the `echo` command instead of hardcoding it](https://stackoverflow.com/questions/8465006/how-do-i-concatenate-two-strings-in-c). – ggorlen Apr 13 '20 at 20:44

0 Answers0