Didn"t forge 2018-11-05 03:23 采纳率: 25%
浏览 301
已采纳

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条回答 默认 最新

  • 关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来