0

I am working on a program that takes a mathematical expression, transforms it to posfix notation and then solves it.

First I am checking the expression to see if it is well formed ( Open brackets and parenthesis matches the closing ones ). To do the part of checking I used fgets() to get the string, because it ignores white spaces as far as I know.

Now I have to break the string when a white space shows up, but for this part would be easier to use a do while using the buffer of a scanf( "%s" ,...)

Is there any way that I can use the scanf trick to break the string, work on int part by part without reading it again?

Aracthor
  • 5,757
  • 6
  • 31
  • 59

2 Answers2

1

You can use sscanf() to advance through a buffer read by fgets()
%n will receive the number of characters used by the scan. Adding used to the offset will advance the scan through the buffer.

int offset = 0;
int used = 0;
char line[1000];
char item[200];
fgets ( line, sizeof ( line), stdin);
while ( ( sscanf ( line + offset, "%199s%n", item, &used)) == 1) {
    offset += used;
    // do something with item
}
user3121023
  • 8,181
  • 5
  • 18
  • 16
0

You can use a buffer to store all the data that is read at the first time using the fgets(); function.

So if the expression is well formed you already have the data, and do not need to read it

The algorithm would be: Use the fgets() to get each part of the expression Store in a buffer variable separating then using a space or another character If the expression is well formed, get the buffer Read each part of the buffer that is separated with space and put then in a new int variable (or array) Compute the expression using this variables (or array)

look this 2 function, they may help you

http://www.cplusplus.com/reference/string/string/find/ http://www.cplusplus.com/reference/string/string/substr/

Lucas Sodré
  • 77
  • 11