for a homework, we need to input simple formulas (such as 3*2, 4+10, 50/16, etc.) and calculate the result (and rest) using only addition, subtraction, and bit shifting. Anyway, I could use three subsequent input reading, however I thought I’d try getting the formula in one pass using fgets() and sscanf(). Here is what I have :
int *v; // value (left side)
int *m; // modifier (right side)
char *o; // operant
int res = sscanf(buffer,"%d%s%d",v,o,m);
But naturally, this does not work, because o gets all the remaining portion of the string, leaving m with nothing (m equals whatever value is where and when it is declared)
Now, what would be the proper way to accomplish this?
NOTE : I’m using a trim function to trim extra spaces.
Try
%cinstead of%s. If the operator is always a single character, and there are no spaces between the operator and the operands, this should work.By the way, are you initializing
v,m, andoto actually point to something? It would be much better to do this:As my “Intro to Programming in C” professor used to say: “C is dangerous. Practice safe C!”.