[英]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. 我正在编写一个程序,以便从stdin
读取内容,然后将读取的内容写入stdout
,以转义找到的所有转义十六进制数字。 All the numbers i want to read are 8 bit. 我要读取的所有数字都是8位。 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. 除了我在标准输入中写入类似%FFF
之类的内容时,它会以3位数的十六进制数字读取的事实有效。 How should i limit fscanf
to reading only 2 characters? 我应该如何限制fscanf
仅读取2个字符? I have thought about reading the next 2 characters into a buffer and sscanf'ing
that, but it feels rather inelegant to me. 我曾考虑过将接下来的2个字符读入缓冲区并sscanf'ing
,但这对我来说感觉并不好。
If you want scanf
(et al) to read only two characters, then tell it to do so: 如果您想让scanf
(et al)仅读取两个字符,请告诉它这样做:
scanf("%2x", &r);
See eg this reference for information about the scanf
formatting. 有关scanf
格式的信息,请参阅此参考 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.