开发者

help with scanf hex in C [closed]

开发者_如何学JAVA This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

i am trying to scan an input file with such format

r1 = 0c100009

So far I have tried this but the while loop is skipped and the output is 0.

    int
    read_reg (reg_t reg) {
    char r, eq;
      int i, hex;
      while (scanf("%c,%d,%[=],%x", &r, &i, &eq, &hex)==4) {
          if ((r != 'r') || (i < 1) || (i > 31) || (eq != '=')){
              error();
          }
          reg[i] = hex;
      }
      printf("%#x\n",hex);
      return 0;
    }

Thanks for the help!


Simplify the scanf argument:

while(scanf("r%d = %x", &i, &hex)==2)

And what do you want to happen if i is outside limits? Should error() be called and what then? Probably not calling reg[i] = hex;.


Your input does not have the commas that the format string requires. You need to remove the first comma and replace the others with blanks.

Also, the %[=] conversion specifier generates a string, not a single character; you need to define char eq[2]; and remove the ampersand when passing eq to scanf().

And, when debugging such stuff, make sure you capture the return from scanf() so you can report how badly things went wrong.

Note that you will be allowing considerable flexibility in the inputs even so:

if  ((n = scanf("%c%d %[=] %x", &r, &i, eq, &hex)) == 4)
    printf("Got: %c%d %s 0x%08X\n", r, i, eq, hex);
else
    printf("Got: n = %d\n", n);

The format string allows all of these lines through as valid:

r1 = 0c100009
r2  =  0c100009
r3=0c100009
r 4=0c100009

In particular, disallowing 'r 4' will be difficult with the scanf() family of functions.


Your scanf() format has all kinds of requirements that your input doesn't have... try getting rid of commas and square braces.

Regarding the braces... you seem to want to make the equals sign optional, but you cannot do that in a scanf. However, you could just scan in the entire line and then pass it through a regular expression matcher.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜