开发者

What is the difference between these three fscanf calls in OCaml?

I wrote a short bit of code to simply skip num_lines lines in an input file (printing the lines out for debugging purposes. Here's two things I tried that didn't work:

for i = 0 to num_lines do
  print_endline (fscanf infile "%s" (fun p -> p));
done;;

for i = 0 to num_开发者_如何转开发lines do
  print_endline (fscanf infile "%S\n" (fun p -> p));
done;;

But this one did work:

for i = 0 to num_lines do
  print_endline (fscanf infile "%s\n" (fun p -> p));
done;;

I've been trying to comprehend the documentation on fscanf, but it doesn't seem to be sinking in. Could someone explain to me exactly why the last snippet worked, but the first two didn't?


"%s" -- Matches everything to next white-space ("\n" here) but never matches "\n"

"%S\n" -- Matches thing that looks like Ocaml strings, then a "\n"

"%s\n" -- Matches everything to next white-space ("\n" here) then "\n". This will act different if there is no trailing "\n" in file or if there is a space before the "\n", etc.

"%s " -- Matches anything up to white-space, and then all trailing white-space including "\n" (or possibly even no white-space). This works because " " means "any white space, possible none", in the format string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜