Cit5
Cit5

Reputation: 440

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

I have an input file that I scan each line until the end. I use the first character as an indicator as what I want to do: 1. paused for x cycles, 2. write a 16-bit word serially, 3. write one bit at a time, 4 end of file.

The issue is that I see an extra mode in between the first p to w transition.

I tried printing out the string value of my variable "mode" but what I see is printed on the wave in between the first p and w is an additional mode not specified in my case statement.

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

input file:

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

I have my systemverilog code that is suppose to scan the input file:

$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

Expected:

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)

Actual:

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)

Upvotes: 0

Views: 1168

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126536

When you use %c in scanf it will read the very next character. When you use %h it will read a hex value, stopping after the last valid hex digit, and not reading what is next. So after your first fscanf call, the input will be pointing at the newline a the end of the first line, and the next fscanf call will read that newline with %c, and you'll get mode == "\n"

What you probably want is to use " %c%h" as your format -- note the (space) before the %c. The space causes fscanf to read and discard whitespace. Since %h automatically skips whitespace before reading a number, you don't need the space before it.

Upvotes: 3

Related Questions