℡Wang Yan 2018-11-05 03:23 采纳率: 100%
浏览 312
已采纳

sscanf() skipping delimiter & width

I am writing an assembler for 6502 and trying to read the instructions and opcode data from a file I prepared. Using sscanf to store data and it only worked partially...

File:

ADC,Im,69,2    
ADC,ZP,65,2
ADC,ZPx,75,2
ADC,Ab,6D,3
ADC,Abx,7D,3
ADC,Aby,79,3
...

Here is only part of the code related to the problem. fgets works fine. Problem line commented below. Will upload more if needed.

Code:

  FILE *fp = ...
  char bf[15];
  char name[3];
  char mode[3];
  char op[2];
  int bytes;

  while (fgets(bf,15,fp)) {
    //below is the problem line
    sscanf(bf, "%3[^,],%3[^,],%2[^,],%d", name, mode, op, &bytes);
  }
  printf("%s,%s,%s,%d\n", name, mode, op, bytes);

Output:

ADCIm,Im,69,2
ADCZP,ZP,65,2
ADCZPx75,ZPx75,75,2
ADCAb,Ab,6D,3
ADCAbx7D,Abx7D,7D,3
...

Expected to be (just like the file format):

ADC,Im,69,2
ADC,ZP,65,2
ADC,ZPx75,75,2
ADC,Ab,6D,3
ADC,Abx7D,7D,3
...

It seems that op and bytes all work alright, but there are something wrong with the name and mode variables, even though I contained the width and delimiter in the argument.

转载于:https://stackoverflow.com/questions/53147902/sscanf-skipping-delimiter-width

  • 写回答

1条回答 默认 最新

  • derek5. 2018-11-05 03:33
    关注

    Actually, it's not sscanf that is at fault. You have undefined behavior due to buffer overruns -- printf knows nothing about the fact that your strings are not null-terminated, and it will continue printing characters until it finds a '\0'.

    To stop it from doing that, you can supply a maximum field width in the format specifier:

    printf("%.3s,%.3s,%.2s,%d\n", name, mode, op, bytes);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢