📅  最后修改于: 2020-11-21 06:57:13             🧑  作者: Mango
基本输入输出包括-
我们已经使用了printf和printfn函数来写入控制台。在本节中,我们将研究F#的Printf模块的详细信息。
除上述功能外,F#的Core.Printf模块还具有其他各种使用%标记作为占位符进行打印和格式化的方法。下表显示了具有简要说明的方法-
Value | Description |
---|---|
bprintf : StringBuilder → BuilderFormat<‘T> → ‘T | Prints to a StringBuilder. |
eprintf : TextWriterFormat<‘T> → ‘T | Prints formatted output to stderr. |
eprintfn : TextWriterFormat<‘T> → ‘T | Prints formatted output to stderr, adding a newline. |
failwithf : StringFormat<‘T,’Result> → ‘T | Prints to a string buffer and raises an exception with the given result. |
fprintf : TextWriter → TextWriterFormat<‘T> → ‘T | Prints to a text writer. |
fprintfn : TextWriter → TextWriterFormat<‘T> → ‘T | Prints to a text writer, adding a newline. |
kbprintf : (unit → ‘Result) → StringBuilder → BuilderFormat<‘T,’Result> → ‘T | Like bprintf, but calls the specified function to generate the result. |
kfprintf : (unit → ‘Result) → TextWriter → TextWriterFormat<‘T,’Result> → ‘T | Like fprintf, but calls the specified function to generate the result. |
kprintf : (string → ‘Result) → StringFormat<‘T,’Result> → ‘T | Like printf, but calls the specified function to generate the result. For example, these let the printing force a flush after all output has been entered onto the channel, but not before. |
ksprintf : (string → ‘Result) → StringFormat<‘T,’Result> → ‘T | Like sprintf, but calls the specified function to generate the result. |
printf : TextWriterFormat<‘T> → ‘T | Prints formatted output to stdout. |
printfn : TextWriterFormat<‘T> → ‘T | Prints formatted output to stdout, adding a newline. |
sprintf : StringFormat<‘T> → ‘T | Prints to a string by using an internal string buffer and returns the result as a string. |
格式规范用于根据程序员的需要来格式化输入或输出。
这些是带有%标记的字符串,指示格式占位符。
格式占位符的语法是-
%[flags][width][.precision][type]
该类型被解释为-
Type | Description |
---|---|
%b | Formats a bool, formatted as true or false. |
%c | Formats a character. |
%s | Formats a string, formatted as its contents, without interpreting any escape characters. |
%d, %i | Formats any basic integer type formatted as a decimal integer, signed if the basic integer type is signed. |
%u | Formats any basic integer type formatted as an unsigned decimal integer. |
%x | Formats any basic integer type formatted as an unsigned hexadecimal integer, using lowercase letters a through f. |
%X | Formats any basic integer type formatted as an unsigned hexadecimal integer, using uppercase letters A through F. |
%o | Formats any basic integer type formatted as an unsigned octal integer. |
%e, %E, %f, %F, %g, %G | Formats any basic floating point type (float, float32) formatted using a C-style floating point format specifications. |
%e, %E | Formats a signed value having the form [-]d.dddde[sign]ddd where d is a single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or -. |
%f | Formats a signed value having the form [-]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision. |
%g, %G | Formats a signed value printed in f or e format, whichever is more compact for the given value and precision. |
%M | Formats a Decimal value. |
%O | Formats any value, printed by boxing the object and using its ToString method. |
%A, %+A | Formats any value, printed with the default layout settings. Use %+A to print the structure of discriminated unions with internal and private representations. |
%a |
A general format specifier, requires two arguments. The first argument is a function which accepts two arguments: first, a context parameter of the appropriate type for the given formatting function (for example, a TextWriter), and second, a value to print and which either outputs or returns appropriate text. The second argument is the particular value to print. |
%t | A general format specifier, requires one argument: a function which accepts a context parameter of the appropriate type for the given formatting function (aTextWriter) and which either outputs or returns appropriate text. Basic integer types are byte, sbyte, int16, uint16, int32, uint32, int64, uint64, nativeint, and unativeint. Basic floating point types are float and float32. |
宽度是可选参数。它是一个整数,指示结果的最小宽度。例如,%5d打印一个至少有5个字符的空格的整数。
下表描述了有效标志–
Value | Description |
---|---|
0 | Specifies to add zeros instead of spaces to make up the required width. |
– | Specifies to left-justify the result within the width specified. |
+ | Specifies to add a + character if the number is positive (to match a – sign for negative numbers). |
‘ ‘ (space) | Specifies to add an extra space if the number is positive (to match a – sign for negative numbers). |
# | Invalid. |
printf "Hello "
printf "World"
printfn ""
printfn "Hello "
printfn "World"
printf "Hi, I'm %s and I'm a %s" "Rohit" "Medical Student"
printfn "d: %f" 212.098f
printfn "e: %f" 504.768f
printfn "x: %g" 212.098f
printfn "y: %g" 504.768f
printfn "x: %e" 212.098f
printfn "y: %e" 504.768f
printfn "True: %b" true
编译并执行程序时,将产生以下输出-
Hello World
Hello
World
Hi, I'm Rohit and I'm a Medical Studentd: 212.098000
e: 504.768000
x: 212.098
y: 504.768
x: 2.120980e+002
y: 5.047680e+002
True: true
此类是.NET框架的一部分。它代表控制台应用程序的标准输入,输出和错误流。
它提供了各种从控制台读取和写入控制台的方法。下表显示了方法-
Method | Description |
---|---|
Beep() | Plays the sound of a beep through the console speaker. |
Beep(Int32, Int32) | Plays the sound of a beep of a specified frequency and duration through the console speaker. |
Clear | Clears the console buffer and corresponding console window of display information. |
MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32) | Copies a specified source area of the screen buffer to a specified destination area. |
MoveBufferArea(Int32, Int32, Int32, Int32, Int32, Int32, Char, ConsoleColor, ConsoleColor) | Copies a specified source area of the screen buffer to a specified destination area. |
OpenStandardError() | Acquires the standard error stream. |
OpenStandardError(Int32) | Acquires the standard error stream, which is set to a specified buffer size. |
OpenStandardInput() | Acquires the standard input stream. |
OpenStandardInput(Int32) | Acquires the standard input stream, which is set to a specified buffer size. |
OpenStandardOutput() | Acquires the standard output stream. |
OpenStandardOutput(Int32) | Acquires the standard output stream, which is set to a specified buffer size. |
Read | Reads the next character from the standard input stream. |
ReadKey() | Obtains the next character or function key pressed by the user. The pressed key is displayed in the console window. |
ReadKey(Boolean) | Obtains the next character or function key pressed by the user. The pressed key is optionally displayed in the console window. |
ReadLine | Reads the next line of characters from the standard input stream. |
ResetColor | Sets the foreground and background console colors to their defaults. |
SetBufferSize | Sets the height and width of the screen buffer area to the specified values. |
SetCursorPosition | Sets the position of the cursor. |
SetError | Sets the Error property to the specified TextWriter object. |
SetIn | Sets the In property to the specified TextReader object. |
SetOut | Sets the Out property to the specified TextWriter object. |
SetWindowPosition | Sets the position of the console window relative to the screen buffer. |
SetWindowSize | Sets the height and width of the console window to the specified values. |
Write(Boolean) | Writes the text representation of the specified Boolean value to the standard output stream. |
Write(Char) | Writes the specified Unicode character value to the standard output stream. |
Write(Char[]) | Writes the specified array of Unicode characters to the standard output stream. |
Write(Decimal) | Writes the text representation of the specified Decimal value to the standard output stream. |
Write(Double) | Writes the text representation of the specified double-precision floating-point value to the standard output stream. |
Write(Int32) | Writes the text representation of the specified 32-bit signed integer value to the standard output stream. |
Write(Int64) | Writes the text representation of the specified 64-bit signed integer value to the standard output stream. |
Write(Object) | Writes the text representation of the specified object to the standard output stream. |
Write(Single) | Writes the text representation of the specified single-precision floating-point value to the standard output stream. |
Write(String) | Writes the specified string value to the standard output stream. |
Write(UInt32) | Writes the text representation of the specified 32-bit unsigned integer value to the standard output stream. |
Write(UInt64) | Writes the text representation of the specified 64-bit unsigned integer value to the standard output stream. |
Write(String, Object) | Writes the text representation of the specified object to the standard output stream using the specified format information. |
Write(String, Object[]) | Writes the text representation of the specified array of objects to the standard output stream using the specified format information. |
Write(Char[], Int32, Int32) | Writes the specified subarray of Unicode characters to the standard output stream. |
Write(String, Object, Object) | Writes the text representation of the specified objects to the standard output stream using the specified format information. |
Write(String, Object, Object, Object) | Writes the text representation of the specified objects to the standard output stream using the specified format information. |
Write(String, Object, Object, Object, Object) | Writes the text representation of the specified objects and variable-length parameter list to the standard output stream using the specified format information. |
WriteLine() | Writes the current line terminator to the standard output stream. |
WriteLine(Boolean) | Writes the text representation of the specified Boolean value, followed by the current line terminator, to the standard output stream. |
WriteLine(Char) | Writes the specified Unicode character, followed by the current line terminator, value to the standard output stream. |
WriteLine(Char[]) | Writes the specified array of Unicode characters, followed by the current line terminator, to the standard output stream. |
WriteLine(Decimal) | Writes the text representation of the specified Decimal value, followed by the current line terminator, to the standard output stream. |
WriteLine(Double) | Writes the text representation of the specified double-precision floating-point value, followed by the current line terminator, to the standard output stream. |
WriteLine(Int32) | Writes the text representation of the specified 32-bit signed integer value, followed by the current line terminator, to the standard output stream. |
WriteLine(Int64) | Writes the text representation of the specified 64-bit signed integer value, followed by the current line terminator, to the standard output stream. |
WriteLine(Object) | Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream. |
WriteLine(Single) | Writes the text representation of the specified single-precision floating-point value, followed by the current line terminator, to the standard output stream. |
WriteLine(String) | Writes the specified string value, followed by the current line terminator, to the standard output stream. |
WriteLine(UInt32) | Writes the text representation of the specified 32-bit unsigned integer value, followed by the current line terminator, to the standard output stream. |
WriteLine(UInt64) | Writes the text representation of the specified 64-bit unsigned integer value, followed by the current line terminator, to the standard output stream. |
WriteLine(String, Object) | Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information. |
WriteLine(String, Object[]) | Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information. |
WriteLine(Char[], Int32, Int32) | Writes the specified subarray of Unicode characters, followed by the current line terminator, to the standard output stream. |
WriteLine(String, Object, Object) | Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information. |
WriteLine(String, Object, Object, Object) | Writes the text representation of the specified objects, followed by the current line terminator, to the standard output stream using the specified format information. |
WriteLine(String, Object, Object, Object, Object) | Writes the text representation of the specified objects and variable-length parameter list, followed by the current line terminator, to the standard output stream using the specified format information. |
以下示例演示了如何从控制台读取并写入控制台-
open System
let main() =
Console.Write("What's your name? ")
let name = Console.ReadLine()
Console.Write("Hello, {0}\n", name)
Console.WriteLine(System.String.Format("Big Greetings from {0} and {1}", "TutorialsPoint", "Absoulte Classes"))
Console.WriteLine(System.String.Format("|{0:yyyy-MMM-dd}|", System.DateTime.Now))
main()
编译并执行程序时,将产生以下输出-
What's your name? Kabir
Hello, Kabir
Big Greetings from TutorialsPoint and Absoulte Classes
|2015-Jan-05|
System.IO命名空间包含各种用于执行基本I / O的有用类。
它包含允许对文件和数据流进行读写的类型或类,以及提供基本文件和目录支持的类型。
对使用文件系统有用的类-
对于处理流有用的类(字节序列)-
下表显示了命名空间中提供的所有类以及简要说明-
Class | Description |
---|---|
BinaryReader | Reads primitive data types as binary values in a specific encoding. |
BinaryWriter | Writes primitive types in binary to a stream and supports writing strings in a specific encoding. |
BufferedStream | Adds a buffering layer to read and write operations on another stream. |
Directory | Exposes static methods for creating, moving, and enumerating through directories and subdirectories. |
DirectoryInfo | Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. |
DirectoryNotFoundException | The exception that is thrown when part of a file or directory cannot be found. |
DriveInfo | Provides access to information on a drive. |
DriveNotFoundException | The exception that is thrown when trying to access a drive or share that is not available. |
EndOfStreamException | The exception that is thrown when reading is attempted past the end of a stream. |
ErrorEventArgs | Provides data for the FileSystemWatcher.Error event. |
File | Provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects. |
FileFormatException | The exception that is thrown when an input file or a data stream that is supposed to conform to a certain file format specification is malformed. |
FileInfo | Provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. |
FileLoadException | The exception that is thrown when a managed assembly is found but cannot be loaded. |
FileNotFoundException | The exception that is thrown when an attempt to access a file that does not exist on disk fails. |
FileStream | Exposes a Stream around a file, supporting both synchronous and asynchronous read and write operations. |
FileSystemEventArgs | Provides data for the directory events − Changed, Created, Deleted. |
FileSystemInfo | Provides the base class for both FileInfo and DirectoryInfo objects. |
FileSystemWatcher | Listens to the file system change notifications and raises events when a directory, or file in a directory, changes. |
InternalBufferOverflowException | The exception thrown when the internal buffer overflows. |
InvalidDataException | The exception that is thrown when a data stream is in an invalid format. |
IODescriptionAttribute | Sets the description visual designers can display when referencing an event, extender, or property. |
IOException | The exception that is thrown when an I/O error occurs. |
MemoryStream | Creates a stream whose backing store is memory. |
Path | Performs operations on String instances that contain file or directory path information. These operations are performed in a cross-platform manner. |
PathTooLongException | The exception that is thrown when a path or file name is longer than the system-defined maximum length. |
PipeException | Thrown when an error occurs within a named pipe. |
RenamedEventArgs | Provides data for the Renamed event. |
Stream | Provides a generic view of a sequence of bytes. This is an abstract class. |
StreamReader | Implements a TextReader that reads characters from a byte stream in a particular encoding. |
StreamWriter | Implements a TextWriter for writing characters to a stream in a particular encoding. To browse the .NET Framework source code for this type, see the Reference Source. |
StringReader | Implements a TextReader that reads from a string. |
StringWriter | Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder. |
TextReader | Represents a reader that can read a sequential series of characters. |
TextWriter | Represents a writer that can write a sequential series of characters. This class is abstract. |
UnmanagedMemoryAccessor | Provides random access to unmanaged blocks of memory from managed code. |
UnmanagedMemoryStream | Provides access to unmanaged blocks of memory from managed code. |
WindowsRuntimeStorageExtensions | Contains extension methods for the IStorageFile and IStorageFolder interfaces in the Windows Runtime when developing Windows Store apps. |
WindowsRuntimeStreamExtensions | Contains extension methods for converting between streams in the Windows Runtime and managed streams in the .NET for Windows Store apps. |
以下示例创建一个名为test.txt的文件,在该文件中写入一条消息,从该文件中读取文本并将其打印在控制台上。
注意-做到这一点所需的代码量惊人地少了!
open System.IO // Name spaces can be opened just as modules
File.WriteAllText("test.txt", "Hello There\n Welcome to:\n Tutorials Point")
let msg = File.ReadAllText("test.txt")
printfn "%s" msg
编译并执行程序时,将产生以下输出-
Hello There
Welcome to:
Tutorials Point