简体   繁体   中英

How should i limit the number of characters interpretted by fscanf?

I'm writing a program to read from stdin and then writes what it reads to stdout , unescaping any escaped hex numbers it finds. All the numbers i want to read are 8 bit. This is what i have so far

while((c = fgetc(stdin)) != EOF) {
    if(c == '%') {
        fscanf(stdin,"%x",&r);
        printf("%i \n",r);
    }
}

This works fine, except for the fact that when i write something like %FFF to the standard input it reads it as a 3 digit hex number. How should i limit fscanf to reading only 2 characters? I have thought about reading the next 2 characters into a buffer and sscanf'ing that, but it feels rather inelegant to me.

If you want scanf (et al) to read only two characters, then tell it to do so:

scanf("%2x", &r);

See eg this reference for information about the scanf formatting.

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