使用 fscanf 时,扫描的行之间发生了什么?

When using fscanf, what is happening inbetween lines being scanned?

我有一个输入文件,我扫描每一行直到结束。我使用第一个字符作为我想要做的指示符:1. 暂停 x 周期,2. 连续写入一个 16 位字,3. 一次写入一位,4 文件结束。

问题是我在第一个 pw 转换之间看到一个额外的模式。

我尝试打印出我的变量的字符串值 "mode" 但我看到的打印在第一个 p 和 w 之间的 wave 是我的 case 语句中未指定的附加模式。

at time = 0: mode equals " " (blank, nothing, all fine) at time = A: mode now equals "p" (暂停了 4 个周期,没问题,我可以稍后修复) at time = B: 模式现在等于“[]”(错误!这不是下一行) 在 time = C: 模式现在等于 "w"(恢复正常)

输入文件:

p 10
w DEAD
w BEEF
p 5
b HHLL
p 100
eol

我有我的 systemverilog 代码,可以扫描输入文件:

$fscanf(fd, "%c %h", mode, mystr);

case(mode)
  "p": begin
    wait_v = mystr.atoi();
    repeat ( wait_v) begin
      //turns bits on or off, but only modifies wire outputs and not mode
    end
  end

  "w": begin
    data = mystr.atohex();
    // writes data, each character is 4 bits. each word is 16 cycles
  end

  "b": begin
    lastsix = mystr.atobin();
    // writes data outputs either high or low, each character is 1 cycle long
  end

  "eol": begin
    $fclose(fn);
    $stop;
  end

预计:

time => 0: mode equals " " (blank, nothing, all fine)
time => A: mode now equals "p" (paused for 3 cycles)
time => C: mode now equals "w" (back to normal)

实际:

time => 0: mode equals " " (blank, nothing, all fine)
time => A: mode now equals "p" (paused 4 cycles long, sure fine, I can fix this later)
time => B: mode now equals "[]" (ERROR! this is not the next line)
time => C: mode now equals "w" (back to normal)

当您在 scanf 中使用 %c 时,它将读取下一个字符。当您使用 %h 时,它将读取一个十六进制值,在最后一个有效的十六进制数字之后停止,并且 而不是 读取下一个。所以在你第一次 fscanf 调用之后,输入将指向第一行末尾的换行符,下一个 fscanf 调用将读取带有 %c 的换行符,你将得到 mode == "\n “

您可能想要使用 " %c%h" 作为您的格式——请注意 %c 之前的 </code> (space)。 space 导致 fscanf 读取并丢弃 whitespace。由于 <code>%h 在读取数字之前会自动跳过白色 space,因此您 不需要 前面的 space。