I want to write a C program that takes a simple math problem from the user and use different processes to solve each part, and then send the value back to the parent process. This program should not pay attention to the order of operations. For instance, if I have the problem:
3 + 4 / 7 + 4 * 2
I want my program to output the following:
Enter problem: 3 + 4 / 7 + 4 * 2
PID 20419 calculated 3+4 as 7
PID 20420 calculated 7/7 as 1
PID 20421 calculated 1+4 as 5
PID 20422 calculated 5*2 as 10
Final result: 10
I am having a bit of trouble parsing the equation I am entering. I am thinking of using the getline()
method in C to help me parse input. This is what I have so far:
#include <stdio.h>
#define MAX_LINE_LENGTH 200
int main()
{
printf("Enter equation: ");
//getline(&buffer, &size, stdin)
//&buffer is the address of the first character
//&size is the address of the variable that holds the size of the input buffer
//stdin is the input file handle
size_t n = MAX_LINE_LENGTH;
//Line becomes a pointer to 200 bytes of memory for you to use
char *line = malloc(n)
while ((getline(&line, &n, stdin)) {
//Parse numbers and operators here
}
return 0;
}
Does anyone have any suggestions on how to parse the numbers and operators that I will enter from the standard input? Once I think I read in a number, operator, and a number, I would like to use fork()
. Thank you all in advance.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…