1

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.

Community
  • 1
  • 1
Yanick Rochon
  • 51,409
  • 25
  • 133
  • 214

3 Answers3

2

Try %c instead 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, and o to actually point to something? It would be much better to do this:

int v;
int m
char o;

int res = sscanf(buffer, "%d%c%d", &v, &o, &m);

As my "Intro to Programming in C" professor used to say: "C is dangerous. Practice safe C!".

Dima
  • 38,860
  • 14
  • 75
  • 115
  • 1
    I omitted how the initial variables are declared (they are not pointers initially, but I pass their pointer to a function where `sscanf()` sits) – Yanick Rochon Nov 18 '10 at 14:44
  • Ok. Just checking. This is such an common mistake, that I had to ask. – Dima Nov 18 '10 at 14:47
1

You may use %[-+*/] (with your set of operators) to ensure, that operator string gets only operator characters.

Vovanium
  • 3,798
  • 17
  • 23
0

Since you don't have extraneous spaces and operators are all one character long, you could use %c to fill in o.

nmichaels
  • 49,466
  • 12
  • 107
  • 135