Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Pascal Programming/Input and Output

From Wikibooks, open books for an open world
<Pascal Programming

We already have been usingI/O since the first chapter, but only to get going.It is time to dig a little bit deeper, so we can write nicer programs.

Interface

[edit |edit source]

In its heydays Pascal was so smart and defined a minimal common, yet convenient interface to interact withI/O.Despite various standardization effortsI/O operations differ among every singleOS, yet – as part of the language – Pascal defines a set of operations to be present, regardless of the utilized compiler orOS.

Special files

[edit |edit source]

In thefirst chapter it was already mentioned thatinput andoutput are special program parameters.If you list them in the program parameter list, you can use these identifiers to write and read from the terminal, theCLI you are using.

Text files

[edit |edit source]

In fact,input andoutput are variables.Their data type istext.We call a variable that has the data typetext atext file.

The data of atext file are composed oflines.Aline is a (possibly empty) sequence of characters (e. g. letters, digits, spaces or punctuation) until and including a terminating “newline character”.

Files

[edit |edit source]

A file – in general – has the following properties:

  • It can be associated with an external entity.External means “outside” of your program. A suitableentity can be, for instance, your console window, a device such as your keyboard, or a file that resides in your file system.
  • If a file is associated with an external entity, it is consideredbound.
  • A file has amode. Every file can be ingeneration orinspection mode, none or both. If a file is in generationand inspection mode at the same time, this can also be calledupdate mode.[fn 1]
  • Every file has abuffer. This buffer is a temporary storage for writing or reading data, so virtually another variable. This buffer variable exists due to reasons howI/O on computers works.

All this information isimplicitly available to you, you do not need to take care of it.You can query and alter some information in predefined ways.

All you have to keep in mind in order to successfully use files is that a filehas a mode.The text filesinput andoutput are, once they are listed in the program parameter list, in inspection and generation mode respectively.You canonlyread data from files that are inspection mode.And it is only possible towrite datato files that are generation mode.

Note, due to their special nature the mode ofinput andoutput cannot be changed.

Routines

[edit |edit source]

Pascal defines the following routines to read and write to files:

  • get,
  • put,
  • read/readLn, and
  • write/writeLn.

The routinesreadLn andwriteLn can only be used in conjunction with text files, whereas all other routines work withany kind of file.In the following sections we will focus onread andwrite.These routines build upon the “low-level”get andput.In thechapter “Files” we will take a look at them, though.

Writing data

[edit |edit source]

Let’s look at a simple program:

programwriteDemo(output);varx:integer;beginx:=10;writeLn(output,x:20);end.

Copy the program and see what it does.

Assignment

[edit |edit source]

First, we will learn a new statement, the assignment.Colon equals (:=) is read as “becomes”.In the linex := 10 the variable’s valuebecomes ten.On the left hand side you write a variable name.On the right hand side you put a value.The value has to be valid for the variable’s data type.For instance, you couldnot assign'Hello world!' to the variablex, because it is not a validinteger, i. e. the data typex has.

Converting output

[edit |edit source]

The power ofwrite/writeLn is that – for text files – it converts the parameters into a human-readable form.On modern computers theinteger valueten is stored in a particularbinary form.00001010 is a visual representation of the bits set (1) and unset (0) for storing “ten”.Yet, despite the binary storage the characters you see on the screen are10.This conversion, from zeroes and ones into a human-readable representation, the character sequence “10”, is doneautomatically.

NoteIf the destination ofwrite/writeLn is a text file, all parameters are converted into ahuman-readable form provided such conversion is necessary and makes sense.

Formatting output

[edit |edit source]

Furthermore, after the parameterx comes :20.As you might have noticed, when you run the program the value ten is printed right-aligned making the 0 in 10 appear at the 20th column (position from the left margin).

The:20 is aformat specifier.It ensures that the given parameter has aminimum width of that many characters and it may fill missing “width” with spaces to left.

NoteFormat specifiers in awrite/writeLn call can only be specified where a human-readable representation is necessary, in other words if the destination is a text file.

Reading data

[edit |edit source]

Look at this program:

programiceCream(input,output);varresponse:char;beginwriteLn('Do you like ice cream?');writeLn('Type “y” for “yes” (“Yummy!”) and “n” for “no”.');writeLn('Confirm your selection by hitting Enter.');readLn(input,response);ifresponse='y'thenbeginwriteLn('Awesome!');end;end.

Requirements

[edit |edit source]

All parameters given toread/readLn have to be variables.The first parameter, thesource, has to be a file variable which is currently in inspection mode.We ensure that by puttinginput into the program parameter list.If the source parameter isinput, you are allowed to omit it, thusreadLn(response) is equivalent toreadLn(input, response).

NoteIf the source is a text file, you can only read values for variables having the data typechar,integer,real, or “string types”. Other variables not compatible to these types cannot be read from a text file. (The term “compatible” will be explained later.)

Branching

[edit |edit source]

A new language construct which we will cover in detail in the next chapter is theif-then-branch.The code afterthen that is surrounded bybegin andend; is only executed ifresponse equals to the character value 'y'.Otherwise, we are polite and do not express our strong disagreement.

Tasks

[edit |edit source]
Can youwrite toinput? Why does / should it work, or not?
You cannotwrite toinput. The text fileinput is, provided it is listed in the program parameter list, ininspection mode. That means you can onlyread data from this text file, neverwrite.
You cannotwrite toinput. The text fileinput is, provided it is listed in the program parameter list, ininspection mode. That means you can onlyread data from this text file, neverwrite.


Can youread to aconstant?
No, all parameters toread/readLnhave to be variables. A constant, per definition, does not change its value during run-time. That means, also the user cannot assign values to a constant.
No, all parameters toread/readLnhave to be variables. A constant, per definition, does not change its value during run-time. That means, also the user cannot assign values to a constant.


Take yourprogram valentine from the first chapter and improve it with knowledge you have learned in this chapter: Make the heart ideogram appear (sort of) centered. Assume a console window width of 80 characters, or any reasonable width.
An improved version may look like this:
programvalentine(output);constwidth=49;beginwriteLn('   ####     ####   ':width);writeLn(' ######## ######## ':width);writeLn('##     ####      ##':width);writeLn('##       #       ##':width);writeLn('##      ILY      ##':width);writeLn(' ##   sweetie   ## ':width);writeLn('  ###         ###  ':width);writeLn('    ###     ###    ':width);writeLn('      ### ###      ':width);writeLn('        ###        ':width);writeLn('         #         ':width);end.
Note the usage of a constant for the formatting width. Use constants whenever you are otherwise repeating values. Do not worry if you did not do that. You will get a sense for that. Also, the string literals can be shorter on theleft side if the longeststring literal is shorter thanwidth (otherwise it does not resemble a heart ideogram anymore):
programvalentine(output);constwidth=49;beginwriteLn('####     ####   ':width);writeLn('######## ######## ':width);writeLn('##     ####      ##':width);writeLn('##       #       ##':width);writeLn('##      ILY      ##':width);writeLn('##   sweetie   ## ':width);writeLn('###         ###  ':width);writeLn('###     ###    ':width);writeLn('### ###      ':width);writeLn('###        ':width);writeLn('#         ':width);end.
Note that the “opening” typewriter apostrophe starts right before first hash mark. Indentation, though, has been preserved, so you can still recognize the heart shape in your source code and do not need to run the program to see it.
An improved version may look like this:
programvalentine(output);constwidth=49;beginwriteLn('   ####     ####   ':width);writeLn(' ######## ######## ':width);writeLn('##     ####      ##':width);writeLn('##       #       ##':width);writeLn('##      ILY      ##':width);writeLn(' ##   sweetie   ## ':width);writeLn('  ###         ###  ':width);writeLn('    ###     ###    ':width);writeLn('      ### ###      ':width);writeLn('        ###        ':width);writeLn('         #         ':width);end.
Note the usage of a constant for the formatting width. Use constants whenever you are otherwise repeating values. Do not worry if you did not do that. You will get a sense for that. Also, the string literals can be shorter on theleft side if the longeststring literal is shorter thanwidth (otherwise it does not resemble a heart ideogram anymore):
programvalentine(output);constwidth=49;beginwriteLn('####     ####   ':width);writeLn('######## ######## ':width);writeLn('##     ####      ##':width);writeLn('##       #       ##':width);writeLn('##      ILY      ##':width);writeLn('##   sweetie   ## ':width);writeLn('###         ###  ':width);writeLn('###     ###    ':width);writeLn('### ###      ':width);writeLn('###        ':width);writeLn('#         ':width);end.
Note that the “opening” typewriter apostrophe starts right before first hash mark. Indentation, though, has been preserved, so you can still recognize the heart shape in your source code and do not need to run the program to see it.


Create a program that draws a 40 by 6 box like the one shown below, but (for educational purposes) we donot want to enter four times 38 spaces in our source code.
o--------------------------------------o|                                      ||                                      ||                                      ||                                      |o--------------------------------------o
If you are stuck, here is a hint.
This is anempty string literal:''. It is two straight typewriter’s apostrophes back-to-back. You can use it in your solution.
This is anempty string literal:''. It is two straight typewriter’s apostrophes back-to-back. You can use it in your solution.
An acceptable implementation could look like this:
programbox(output);constspace=38;beginwriteLn('o--------------------------------------o');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('o--------------------------------------o');end.
The'':space will generate 38 (that is the value of the constantspace) spaces. If you are really smart, you have noticed that the top and bottom edges of the box are thesame literal twice. We can shorten our program even further:
programbox(output);constspace=38;topAndBottomEdge='o--------------------------------------o';beginwriteLn(topAndBottomEdge);writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn(topAndBottomEdge);end.
An acceptable implementation could look like this:
programbox(output);constspace=38;beginwriteLn('o--------------------------------------o');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('o--------------------------------------o');end.
The'':space will generate 38 (that is the value of the constantspace) spaces. If you are really smart, you have noticed that the top and bottom edges of the box are thesame literal twice. We can shorten our program even further:
programbox(output);constspace=38;topAndBottomEdge='o--------------------------------------o';beginwriteLn(topAndBottomEdge);writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn('|','':space,'|');writeLn(topAndBottomEdge);end.

Notes:

  1. “Update” mode is only available in Extended Pascal (ISO standard 10206). In Standard (unextended) Pascal (laid out inISO standard 7185) a file can be either in inspection or generation mode, or none.


Next Page: Expressions and Branches | Previous Page: Variables and Constants
Home: Pascal Programming
Retrieved from "https://en.wikibooks.org/w/index.php?title=Pascal_Programming/Input_and_Output&oldid=4191492"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp