Formatted input and output in Golang

Source: Internet
Author: User
Tags compact fscan numeric lowercase numeric value sprintf

Formatted input and output in Golang

This article turned from: http://zh.golanger.com/pkg/fmt/, and made a partial modification

The "Introduction" FMT Package implements formatted I/O functions, similar to the C printf and scanf.

The format placeholder is derived from C, but is simpler than c. Print placeholder: [General]%v the default format for the corresponding value.

When the structure is printed, the "Plus" mark (%+v) adds the field name% #v the corresponding value of the go syntax means that the%T of the corresponding value of the type of the go syntax represents the percent percent of the literal percentile, not the value of the placeholder [Boolean]%T word True or false.	[integer]%b binary indicates the character%d decimal representation of the corresponding Unicode code point in%c%o Octal represents the character literal of the%q single quotation mark, which is safely escaped by the Go syntax in the hexadecimal notation, in lowercase a-f%x hexadecimal notation, in uppercase a-f%u Unicode format: u+1234, equivalent to "u+%04x "[floating-point and its compound composition]%b no fractional part, exponential two of the power of the scientific notation, and StrConv. The formatfloat ' B ' conversion format is consistent. For example -123456p-78%e scientific notation, for example -1234.456e+78%e scientific notation, for example -1234.456E+78%f has a decimal point but no exponent, for example 123.456%g to choose%e or%f according to the circumstances to produce More compact (no end of 0) output%G Select%E or%f as appropriate to produce a more compact (no end of 0) output [string and byte slice]%s string or slice without interpretation byte%q double quotes around the string, safely escaped by Go syntax%x 10 Hex, lowercase, two characters per byte%x 16, uppercase letters, two characters per byte [pointer]%p hexadecimal representation, prefix 0x [note] there is no ' u ' tag here. If the integers are unsigned, they will be printed as unsigned.

  Similarly, there is no need to specify the size of the operand (int8,int64). The control format for width and precision is in Unicode code point units. (This is different from printf in C, which is in number of bytes.)

Either or either of these can be represented by the characters ' * ', at which point their values are taken from the next operand, and the type of the operand must be int. Control of width and precision toThe Unicode code point is the unit FMT. Printf ("\"%8s\ "\ n", "123456")//Maximum length is 8//"123456" FMT. Printf ("\"%8s\ "\ n", "Hello")//Maximum length of 8//"  Hello"//width and accuracy all available characters ' * ' represent FMT. Printf ("%0*.*f \ n", 8, 3, 13.25)//Total length 8, number of decimal digits 3 FMT. Printf ("%08.3f \ n", 13.25)  ///Total length 8, scale 3//0013.250 for numeric values, the width is the minimum width for which the value occupies the region, and the precision is the number of digits after the decimal point. For%g/%g, however, the precision is the total number of all numbers. For example, for 123.45, format%6.2f will print 123.45, and%.4g will print 123.5.

  The default precision for%e and%f is 6, but for%g, its default precision is the minimum number of digits necessary to determine the value. For most values, the width is the minimum number of characters for the output and, if necessary, fills the formatted form with spaces.

For a string, the precision is the maximum number of characters to output and is truncated if necessary. The width and precision tag string fmt. Printf ("%8q", "abc")    //Minimum length of 8 (including%q quotes characters)//  "ABC" FMT.

  Printf ("%.8q", "1234567890")//Maximum length is 8 (excluding%q quote character)//"12345678" [other marker] + The sign of the total printed value, and for%q (%+Q) only ASCII encoded characters are guaranteed to be output. -Fill space on the right instead of the left (align left to the area) # Alternate Format: Add a leading 0 (% #o) for octal, add a leading 0x (% #x) or 0X (% #X) for hex, remove leading 0x for%p (% #p), and if possible,%q (% #q) prints the original (that is, the inverted quote

  If it is a printable character,%u (% #U) writes out the Unicode encoding of the character (for example, the character X will be printed as u+0078 ' X ').

"(space) to leave blank (% d) for the negative sign omitted in the numeric value; When you print a string or slice in 16 (% x,% x), spaces are separated between the bytes:Fmt. Printf ("% x\n", "Hello")//6c 6c 6f 0 fills leading 0 instead of spaces; for numbers, this moves the fill to the sign after the [note] tag is sometimes ignored by the placeholder, so don't count on them.

  For example, decimal does not have an alternate format, so the% #d behaves the same as%d. For each function of the Printf class, there is a Print function that does not accept any formatting, which is equivalent to applying%v to every operand.

  Another argument function, PRINTLN, inserts a blank between the operands and appends a newline character to the end. Regardless of the placeholder, if the operand is an interface value, its intrinsic value is used, not the interface itself. Therefore: var i interface{} = fmt.

  Printf ("%v\n", I)//will print 23 if an operand implements the Formatter interface, the interface is better used to control formatting. The Jocque (which is implicitly%v for functions such as PRINTLN) is valid for strings (%s%q%v%x), and the following two rules apply: 1. If an operand implements the error interface, the error method can convert the object to a string, which is then entered according to the placeholder

  Row formatting.

  2. If an operand implements the string () string method, the method can convert the object to a string, which is then formatted according to the needs of the placeholder. To avoid this kind of recursion: type X string func (x x) string () string {return Sprintf ("<%s>", X)} needs to be converted before recursion: func (x x ) string () string {return Sprintf ("<%s>", String (x)} [formatted ERROR] If an invalid argument is supplied to the placeholder (for example, a string is supplied to%d), the resulting string contains a description of the problem. As shown in the following example: type error or placeholder unknown:%!verb (type=value) Printf ("%d", HI)//%!d (String=hi) argument too many:%!

(EXTRA Type=value) Printf ("Hi", "guys")//hi%! (EXTRA String=guys) RealToo few arguments:%!verb (MISSING) Printf ("hi%d")//Hi%!d (MISSING) width or precision is not of type int:%! (badwidth) or%!

(BADPREC) Printf ("%*s", 4.5, "HI")//%! (badwidth) Hi Printf ("%.*s", 4.5, "HI")//%!

(BADPREC) Hi all errors start with "%!", sometimes followed by a single character (placeholder), with the end of the description enclosed in parentheses. "Scan" a similar set of functions to produce a value by scanning the formatted text. Scan, Scanf, and Scanln from the OS. Stdin, Fscan, Fscanf, and FSCANLN from the specified IO. Read in reader; Sscan, Sscanf, and Sscanln are read in the arguments string.

  Scanln, Fscanln, and sscanln stop scanning at line breaks and require entries to follow line breaks, Scanf, Fscanf, and Sscanf need to enter newline characters to match the line breaks in the format, and other functions to treat line breaks as spaces. SCANF, FSCANF, and Sscanf parse arguments based on format strings, similar to Printf.

  For example,%x scans an integer as a hexadecimal number, while%V scans the default presentation format for that value. Formatting behaves like Printf, but there are exceptions:%p does not implement%T%e%e%f%f%g%g are fully equivalent, and can scan any floating-point or compound value%s and%v to scan a string with spaces as delimiters

  # and + are not implemented when scanning integers using the%v placeholder, a friendly binary prefix of 0 (octal) and 0x (hexadecimal) is accepted.

  The width is interpreted as the input text (%5s means to read up to 5 runes from the input into a string), while the scan function has no precision syntax (no%5.2f, only%5f). When scanning in a format, all non-empty contiguous whitespace characters (except newline characters) are equivalent to a single space, both in the format and in the input.

  Because of this limitation, the format string literal must match the input text, and if it does not match, the scanning process stops and returns the real parameters that have been scanned. In all the scan parameters, if an operand implements the scan method (that is, it implements the Scanner interface), the operand will use this method to scan its text. In addition, an error is returned if the actual parameter scanned is less than the supplied real parameter.

 All the arguments that need to be scanned must be basic types or types that implement the Scanner interface.

Note: Functions such as Fscan will read more than one character (rune) from the input, so if a loop invokes a scan function, some data in the input may be skipped. Typically, this problem occurs only if there are no whitespace characters in the input data. If the reader provided to Fscan implements the Readrune, the character is read with this method. If the reader also implements the Unreadrune method, the character will be saved with this method, and successive calls will not lose data. If

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.