简体   繁体   中英

fscanf a file with doubles and characters

I have a file which will contains basic mathematical operations. An example:

1 + 23 / 42 * 23

I am scanning the file, putting each "element" into a struct and pushing it onto a stack I created. The problem I have is as follows:

char reading;
while(!feof(fp)) {
  fscanf(fp, "%c", &reading);
  ....

This will scan 1 , + , 2 , 3 instead of 1 , + , 23 . What are other suggestions to use one fscanf and have it iterate and read all the inputs as intended to with respect to their type?

Regards,

fscanf is the wrong tool for this job, because it needs a format string that knows in advance what format to expect. Your best bet is to read a character at a time and build up tokens that you can then interpret, especially if you'll have to accept input like 2+2 (no spaces), or (1 + 23) / 42 , with parentheses.

You should use fscanf() a bit different, like this:

char buf[16];
int val;
char op;

while (!feof(fp)) {
    fscanf("%s ", buf); // Note: Without ' ' the last value would be readed twice
    if (buf[0] == '+' || buf[0] == '-' || buf[0] == '/' || buf[0] == '*') {
        op = buf[0];
        // do something with op
    } else {
        sscanf(buf, "%d", &val);
        // do something with val
    }
}

The size of buf must be something which could store the length of your numbers.

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