質問

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