简体   繁体   中英

How to break a string, that was read using fgets(), using scanf(“%s”,..)

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?

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
}

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM