diff options
author | Rob Pike <r@golang.org> | 2010-06-18 20:37:03 -0700 |
---|---|---|
committer | Rob Pike <r@golang.org> | 2010-06-18 20:37:03 -0700 |
commit | f6a9b809c97e941f2c5947094b921c1082242e0d (patch) | |
tree | f4d4d2dba7d0e6755ddda78163b714eb47871e93 | |
parent | b4567506fd65d31a3b04b83ec853cbfa9f74d02f (diff) | |
download | golang-f6a9b809c97e941f2c5947094b921c1082242e0d.tar.gz |
fmt.Scanf: improve error message when input does not match format
R=rsc
CC=golang-dev
http://codereview.appspot.com/1693043
Committer: Rob Pike <r@golang.org>
-rw-r--r-- | src/pkg/fmt/scan.go | 10 | ||||
-rw-r--r-- | src/pkg/fmt/scan_test.go | 1 |
2 files changed, 7 insertions, 4 deletions
diff --git a/src/pkg/fmt/scan.go b/src/pkg/fmt/scan.go index 883a95d34..87076e8fc 100644 --- a/src/pkg/fmt/scan.go +++ b/src/pkg/fmt/scan.go @@ -885,6 +885,7 @@ func (s *ss) doScan(a []interface{}) (numProcessed int, err os.Error) { // either input or format behave as a single space. This routine also // handles the %% case. If the return value is zero, either format // starts with a % (with no following %) or the input is empty. +// If it is negative, the input did not match the string. func (s *ss) advance(format string) (i int) { for i < len(format) { fmtc, w := utf8.DecodeRuneInString(format[i:]) @@ -919,7 +920,7 @@ func (s *ss) advance(format string) (i int) { inputc := s.mustGetRune() if fmtc != inputc { s.UngetRune(inputc) - return + return -1 } i += w } @@ -940,10 +941,11 @@ func (s *ss) doScanf(format string, a []interface{}) (numProcessed int, err os.E } // Either we failed to advance, we have a percent character, or we ran out of input. if format[i] != '%' { - // Can't advance format. Do we have arguments still to process? - if i < len(a) { - s.errorString("too many arguments for format") + // Can't advance format. Why not? + if w < 0 { + s.errorString("input does not match format") } + // Otherwise at EOF; "too many operands" error handled below break } i++ // % is one byte diff --git a/src/pkg/fmt/scan_test.go b/src/pkg/fmt/scan_test.go index d316f2e4a..f195c0317 100644 --- a/src/pkg/fmt/scan_test.go +++ b/src/pkg/fmt/scan_test.go @@ -303,6 +303,7 @@ var multiTests = []ScanfMultiTest{ ScanfMultiTest{"%d %d %d", "23 18", args(&i, &j), args(23, 18), "too few operands"}, ScanfMultiTest{"%d %d", "23 18 27", args(&i, &j, &k), args(23, 18), "too many operands"}, ScanfMultiTest{"%c", "\u0100", args(&int8Val), nil, "overflow"}, + ScanfMultiTest{"X%d", "10X", args(&intVal), nil, "input does not match format"}, // Bad UTF-8: should see every byte. ScanfMultiTest{"%c%c%c", "\xc2X\xc2", args(&i, &j, &k), args(utf8.RuneError, 'X', utf8.RuneError), ""}, |