innovation_cat
innovation_cat

Reputation: 85

why "%d" is wrong in OCaml scanf format?

when I implement read_int function with ocaml (see below),

let read_int () = Scanf.bscanf Scanf.Scanning.stdin "%d" (fun x -> x)

if the format argument is %d(no space) , the compiler will return failure with the following information:

Exception:
Scanf.Scan_failure
"scanf: bad input at char number 1: ``character '\\n' is not a decimal digit''".

but if I use ' '%d(prefix with space), it is fine, why %d is wrong? what is the difference between %d and ' '%d? . thanks.

Upvotes: 0

Views: 2348

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66818

The scanf format "%d" matches a string of decimal digits. This doesn't include white space. In a scanf format string a space (" ") stands for any amount of white space (spaces, tabs, newlines).

It's not really possible to tell exactly what else is going on, because I don't know what appears on the standard input of your program. Possibly the problem is the '\n' that appears at the end of the previous line.

Update: For what it's worth, I decided long ago (in my C programming days) that scanf causes more problems than it solves. It's particularly bad at handling lines of input. Better to break input into lines by another method and use sscanf (or int_of_string) on the resulting strings.

Upvotes: 3

Related Questions