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

StackOverflow https://stackoverflow.com/questions/17804841

  •  03-06-2022
  •  | 
  •  

سؤال

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 e.g. this reference for information about the scanf formatting.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top