必承其重 | 欲带皇冠 2018-11-05 03:23 采纳率: 0%
浏览 293
已采纳

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

  • 叼花硬汉 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 vscode问题请教
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM