简体   繁体   中英

using fscanf without it eating word

Here's what I want to do: If I have an integer followed by a specific string I want it to not be pushed on to a stack, otherwise I want it to be pushed on the stack. The problem is, when I test the next thing after the integer with fscanf, it "eats" the next thing, and essentially ruins my code. for example:

if(fscanf(read,"%d", &d)) {
        //If next is not the string "dont", then push but dont "eat" dont!
        push(d, write);
    }

Since you're in a file, you can always remember the current position with ftell() and then go back with fseek() .

const long pos = ftell(read);

if(fscanf(read,"%d", &d)) {
    push(d, write);
    fseek(read, pos, SEEK_SET);
}

Use ungetc()

#include <stdio.h>
int ungetc(int c, FILE *stream);

This will allow you to put back one char

char ch;
fscanf(read,"%d%c", &d, &ch);
if (WantToPutChBack(ch)) {
  ungetc(ch, read);
}

You can only put back one char before "getting" again, hope this is enough.

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